ProgramingTip

시간을 찾는 방법은 Android에서 오늘 또는 어제입니다.

bestdevel 2020. 11. 12. 19:26
반응형

시간을 찾는 방법은 Android에서 오늘 또는 어제입니다.


SMS를 보내기위한 응용 프로그램을 개발 중입니다. 현재 시간을 저장하고 데이터베이스에서 시간을 검색하여 보낸 기록 페이지에 표시됩니다. 보낸 내역 페이지에서 메시지를 보낸 시간을 표시하고 싶습니다. 여기에서 메시지가 또는 어제 또는 어제 전송을 확인하고 싶습니다. 어제 보낸 메시지는 "어제 20:00"을 표시해야한다는 뜻이며 어제 전에 보낸 메시지도 "월요일 20:00"을 의미합니다. 어떻게 해야하는지 모르겠습니다. 아는 사람이 있으면 도와주세요.


android.text.format.DateFormat 클래스를 사용하여 쉽게 할 수 있습니다. 이와 같은 것을 시도하십시오.

public String getFormattedDate(Context context, long smsTimeInMilis) {
    Calendar smsTime = Calendar.getInstance();
    smsTime.setTimeInMillis(smsTimeInMilis);

    Calendar now = Calendar.getInstance();

    final String timeFormatString = "h:mm aa";
    final String dateTimeFormatString = "EEEE, MMMM d, h:mm aa";
    final long HOURS = 60 * 60 * 60;
    if (now.get(Calendar.DATE) == smsTime.get(Calendar.DATE) ) {
        return "Today " + DateFormat.format(timeFormatString, smsTime);
    } else if (now.get(Calendar.DATE) - smsTime.get(Calendar.DATE) == 1  ){
        return "Yesterday " + DateFormat.format(timeFormatString, smsTime);
    } else if (now.get(Calendar.YEAR) == smsTime.get(Calendar.YEAR)) {
        return DateFormat.format(dateTimeFormatString, smsTime).toString();
    } else {
        return DateFormat.format("MMMM dd yyyy, h:mm aa", smsTime).toString();
    }
}

내용은 자세한 http://developer.android.com/reference/java/text/DateFormat.html확인 하십시오 .


날짜가 오늘인지 확인 클릭하세요. Android 유틸리티 라이브러리를 사용하세요.

DateUtils.isToday(long timeInMilliseconds)

이 utils 클래스는 최강의 시간에 대해 읽을 수있는 클래스도 제공합니다. 예를 들면

DateUtils.getRelativeTimeSpanString(long timeInMilliseconds) -> "42 minutes ago"

사용할 수있는 몇 가지 변수가 있습니다.

DateUtils 참조


언급 했듯이은 ( 는) 오늘 DateUtils.isToday(d.getTime())인지 확인하는 데입니다 Date d. 그러나 여기에있는 일부 응답은 날짜가 어제인지 확인하는 방법에 대답하지 않습니다. 다음을 사용하여 쉽게 할 수도 있습니다 DateUtils.

public static boolean isYesterday(Date d) {
    return DateUtils.isToday(d.getTime() + DateUtils.DAY_IN_MILLIS);
}

그런 다음 날짜가 내일인지 확인할 수도 있습니다.

public static boolean isTomorrow(Date d) {
    return DateUtils.isToday(d.getTime() - DateUtils.DAY_IN_MILLIS);
}

오늘 DateUtils.isTodayAndroid API 에서 사용할 수 있습니다 .

어제의 경우 해당 코드를 사용할 수 있습니다.

public static boolean isYesterday(long date) {
    Calendar now = Calendar.getInstance();
    Calendar cdate = Calendar.getInstance();
    cdate.setTimeInMillis(date);

    now.add(Calendar.DATE,-1);

    return now.get(Calendar.YEAR) == cdate.get(Calendar.YEAR)
        && now.get(Calendar.MONTH) == cdate.get(Calendar.MONTH)
        && now.get(Calendar.DATE) == cdate.get(Calendar.DATE);
}

주 시도 할 수 있습니다.

Calendar mDate = Calendar.getInstance(); // just for example
if (DateUtils.isToday(mDate.getTimeInMillis())) {
  //format one way
} else {
  //format in other way
}


사용 된 라이브러리 없음


어제

오늘

내일

올해

연도

 public static String getMyPrettyDate(long neededTimeMilis) {
    Calendar nowTime = Calendar.getInstance();
    Calendar neededTime = Calendar.getInstance();
    neededTime.setTimeInMillis(neededTimeMilis);

    if ((neededTime.get(Calendar.YEAR) == nowTime.get(Calendar.YEAR))) {

        if ((neededTime.get(Calendar.MONTH) == nowTime.get(Calendar.MONTH))) {

            if (neededTime.get(Calendar.DATE) - nowTime.get(Calendar.DATE) == 1) {
                //here return like "Tomorrow at 12:00"
                return "Tomorrow at " + DateFormat.format("HH:mm", neededTime);

            } else if (nowTime.get(Calendar.DATE) == neededTime.get(Calendar.DATE)) {
                //here return like "Today at 12:00"
                return "Today at " + DateFormat.format("HH:mm", neededTime);

            } else if (nowTime.get(Calendar.DATE) - neededTime.get(Calendar.DATE) == 1) {
                //here return like "Yesterday at 12:00"
                return "Yesterday at " + DateFormat.format("HH:mm", neededTime);

            } else {
                //here return like "May 31, 12:00"
                return DateFormat.format("MMMM d, HH:mm", neededTime).toString();
            }

        } else {
            //here return like "May 31, 12:00"
            return DateFormat.format("MMMM d, HH:mm", neededTime).toString();
        }

    } else {
        //here return like "May 31 2010, 12:00" - it's a different year we need to show it
        return DateFormat.format("MMMM dd yyyy, HH:mm", neededTime).toString();
    }
}

이 Whtsapp 앱과 같은 오늘, 어제 및 날짜와 같은 값을 얻는 방법입니다.

public String getSmsTodayYestFromMilli(long msgTimeMillis) {

        Calendar messageTime = Calendar.getInstance();
        messageTime.setTimeInMillis(msgTimeMillis);
        // get Currunt time
        Calendar now = Calendar.getInstance();

        final String strTimeFormate = "h:mm aa";
        final String strDateFormate = "dd/MM/yyyy h:mm aa";

        if (now.get(Calendar.DATE) == messageTime.get(Calendar.DATE)
                &&
                ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                &&
                ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {

            return "today at " + DateFormat.format(strTimeFormate, messageTime);

        } else if (
                ((now.get(Calendar.DATE) - messageTime.get(Calendar.DATE)) == 1)
                        &&
                        ((now.get(Calendar.MONTH) == messageTime.get(Calendar.MONTH)))
                        &&
                        ((now.get(Calendar.YEAR) == messageTime.get(Calendar.YEAR)))
                ) {
            return "yesterday at " + DateFormat.format(strTimeFormate, messageTime);
        } else {
            return "date : " + DateFormat.format(strDateFormate, messageTime);
        }
    }

이 방법을 사용하여 Millisecond를 다음과 같이 전달하십시오.

 getSmsTodayYestFromMilli(Long.parseLong("1485236534000"));

    Calendar now = Calendar.getInstance();
    long secs = (dateToCompare - now.getTime().getTime()) / 1000;
    if (secs > 0) {
        int hours = (int) secs / 3600;
        if (hours <= 24) {
            return today + "," + "a formatted day or empty";
        } else if (hours <= 48) {
            return yesterday + "," + "a formatted day or empty";
        }
    } else {
        int hours = (int) Math.abs(secs) / 3600;

        if (hours <= 24) {
            return tommorow + "," + "a formatted day or empty";
        }
    }
    return "a formatted day or empty";

그것을하는 또 다른 방법. 에서 코 틀린 lib에는 추천과 ThreeTen

  1. ThreeTen 추가

    implementation 'com.jakewharton.threetenabp:threetenabp:1.1.0'
    
  2. kotlin 확장을 추가하십시오.

    fun LocalDate.isYesterday(): Boolean = this.isEqual(LocalDate.now().minusDays(1L))
    
    fun LocalDate.isToday(): Boolean = this.isEqual(LocalDate.now())
    

한 가지 제안 할 수 있습니다. SMS를 보낼 때 데이터베이스에 세부 정보를 저장하여 기록 페이지에 SMS가 전송 된 날짜와 시간을 표시 할 수 있습니다.


DateUtils.isToday()android.text.format.Time은 이제 더 이상 사용 되지 않기 때문에 더 이상 사용되지 않는 것으로 간주되어야합니다 . isToday에 대한 소스 코드를 업데이트 할 때까지 어제 오늘을 감지하고 일광 절약 시간과의 교대를 처리하고 더 이상 사용되지 않는 코드를 사용하지 않는 솔루션이 없습니다. today주기적으로 업데이트해야하는 필드를 사용하는 Kotlin에 있습니다 (예 : onResume등).

@JvmStatic
fun dateString(ctx: Context, epochTime: Long): String {
    val epochMS = 1000*epochTime
    val cal = Calendar.getInstance()
    cal.timeInMillis = epochMS
    val yearDiff = cal.get(Calendar.YEAR) - today.get(Calendar.YEAR)
    if (yearDiff == 0) {
        if (cal.get(Calendar.DAY_OF_YEAR) >= today.get(Calendar.DAY_OF_YEAR))
            return ctx.getString(R.string.today)
    }
    cal.add(Calendar.DATE, 1)
    if (cal.get(Calendar.YEAR) == today.get(Calendar.YEAR)) {
        if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR))
            return ctx.getString(R.string.yesterday)
    }
    val flags = if (yearDiff == 0) DateUtils.FORMAT_ABBREV_MONTH else DateUtils.FORMAT_NUMERIC_DATE
    return DateUtils.formatDateTime(ctx, epochMS, flags)
}

https://code.google.com/p/android/issues/detail?id=227694&thanks=227694&ts=1479155729를 제출 했습니다.

참고 URL : https://stackoverflow.com/questions/12818711/how-to-find-time-is-today-or-yesterday-in-android

반응형