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


87

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


당신이 ... 할 것을 코드를 표시하십시오
구피

@Keyser 방법을 알려주시겠습니까?
Manikandan

2
아직 코드를 시도하지 않았으므로 어떤 도움이 필요한지 알 수 없습니다. 질문하는 것은 시기상조입니다. 무엇이 문제를 일으키는 지 볼 때까지 기다리십시오.
David Schwartz

당신이 데이터베이스에서 데이터를 가져올 때마다, 전송 상자에 변환의 마지막 시간을 가져
Nirav Ranpara

@ user1498488 Java 날짜 / 시간 처리에 대한 자습서를 찾으십시오.
keyser 2012.10.10

답변:


51

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 을 확인 하십시오 .


21
맞습니까? 날짜 만 비교하면 연도와 월은 어떻습니까? 오늘은 2014 년
Daryn

3
이 대답은 정확하지 않습니다. 문서에 따라 Calendar.DATE는 DAY_OF_MONTH의 동의어입니다. 따라서 연도와 월을 비교하지 않습니다.
Joao Sousa

네, 정확하지 않습니다. (Calendar.DATE) == smsTime.get (Calendar.DATE)는 월과 연도가 아닌 날짜 만 일치합니다. 2012
Anjum

1
"오늘"텍스트의 경우이 솔루션은 항상 정확하지만 "어제"텍스트의 경우 매월 1 일에는 올바르지 않습니다. get (Calendar.DATE) 메소드는 날짜를 반환합니다. 예를 들어 1-31 = -30 대신 1 "어제"를 표시해야합니다. 12 월 31 일은 1 월 1 일의 전날이기 때문입니다.
lukjar

"오늘"및 "어제"에는 Calendar.DATE
ZakariaBK

242

날짜가 오늘인지 확인하려면 Android utils 라이브러리를 사용하세요.

DateUtils.isToday(long timeInMilliseconds)

이 utils 클래스는 상대적인 시간에 대해 사람이 읽을 수있는 문자열도 제공합니다. 예를 들면

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

시간 범위가 얼마나 정확해야하는지 정의하기 위해 사용할 수있는 몇 가지 매개 변수가 있습니다.

DateUtils 참조


5
DateUtils.isToday (myDate.getTime ())이 잘 작동합니다. 감사합니다!
Loenix

4
로컬 (UTC가 아닌) 시간 또는 UTC 타임 스탬프 만 사용합니까?
Matthias

5
DateUtils.isToday(long millis)@Maragues에서 설명한대로 작동하지만 단위 테스트를 원하는 코드 (예 : ViewModel 또는 Presenter)에서이 메서드를 사용하면 테스트를 실행할 때 RuntimeException이 발생합니다. 이는 단위 테스트에 사용되는 android.jar에 코드가 포함되어 있지 않기 때문입니다. 더 많은 정보 링크
Kaskasi

78

언급했듯이은 ( 는) 오늘 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);
}

이것은 받아 들여진 대답이어야합니다. 읽기 쉽고 효과적입니다. 더 효과적으로 만드는 유일한 방법은 밀리 타임 스탬프에 대한 메서드를 작성하는 것이므로 Calendar, Date 또는 원하는 클래스와 함께 사용할 수 있습니다.
joe1806772

이것은 훌륭합니다. 하지만 이상한 이유로 나는 이것을 Kotlin에서 확장 기능으로 사용할 수 없습니다 :fun DateUtils.isYesterday(d: Long): Boolean { return DateUtils.isToday(d + DateUtils.DAY_IN_MILLIS) }
Saifur Rahman Mohsin

나는 이것이이 일을 얻는 코드 문자 그대로 두 줄 가장 좋은 방법이라고 생각
아미르 도라.

22

오늘 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);
}

@lujpo 완벽!
swooby jul.

now.get (Calendar.MONTH) 위의 코드는 지난달을 반환하는 것 같습니다!?
Tina

@tina 매월 1 일에만 발생해야합니다
lujop

9

이것을 시도 할 수 있습니다.

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

7

API 레벨이 26 이상이면 LocalDate 클래스를 사용하는 것이 좋습니다.

fun isToday(whenInMillis: Long): Boolean {
    return LocalDate.now().compareTo(LocalDate(whenInMillis)) == 0
}

fun isTomorrow(whenInMillis: Long): Boolean {
    return LocalDate.now().plusDays(1).compareTo(LocalDate(whenInMillis)) == 0
}

fun isYesterday(whenInMillis: Long): Boolean {
    return LocalDate.now().minusDays(1).compareTo(LocalDate(whenInMillis)) == 0
}

앱의 API 수준이 낮은 경우

fun isToday(whenInMillis: Long): Boolean {
    return DateUtils.isToday(whenInMillis)
}

fun isTomorrow(whenInMillis: Long): Boolean {
    return DateUtils.isToday(whenInMillis - DateUtils.DAY_IN_MILLIS)
}

fun isYesterday(whenInMillis: Long): Boolean {
    return DateUtils.isToday(whenInMillis + DateUtils.DAY_IN_MILLIS)
} 

5

사용 된 라이브러리 없음


어제

오늘

내일

올해

연도

 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();
    }
}

4

그것을하는 또 다른 방법. 에서 코 틀린 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())
    

이것이 갈 길이되어야합니다. 커스텀 파싱은 나쁘다.
XY

4

Kotlin

@Choletski 솔루션이지만 초 및 Kotlin에서

 fun getMyPrettyDate(neededTimeMilis: Long): String? {
        val nowTime = Calendar.getInstance()
        val neededTime = Calendar.getInstance()
        neededTime.timeInMillis = neededTimeMilis
        return if (neededTime[Calendar.YEAR] == nowTime[Calendar.YEAR]) {
            if (neededTime[Calendar.MONTH] == nowTime[Calendar.MONTH]) {
                if (neededTime[Calendar.DATE] - nowTime[Calendar.DATE] == 1) {
                    //here return like "Tomorrow at 12:00"
                    "Tomorrow at " + DateFormat.format("HH:mm:ss", neededTime)
                } else if (nowTime[Calendar.DATE] == neededTime[Calendar.DATE]) {
                    //here return like "Today at 12:00"
                    "Today at " + DateFormat.format("HH:mm:ss", neededTime)
                } else if (nowTime[Calendar.DATE] - neededTime[Calendar.DATE] == 1) {
                    //here return like "Yesterday at 12:00"
                    "Yesterday at " + DateFormat.format("HH:mm:ss", neededTime)
                } else {
                    //here return like "May 31, 12:00"
                    DateFormat.format("MMMM d, HH:mm:ss", neededTime).toString()
                }
            } else {
                //here return like "May 31, 12:00"
                DateFormat.format("MMMM d, HH:mm:ss", neededTime).toString()
            }
        } else {
            //here return like "May 31 2010, 12:00" - it's a different year we need to show it
            DateFormat.format("MMMM dd yyyy, HH:mm:ss", neededTime).toString()
        }
    }

여기 date.getTime()를 통과 하여 다음과 같은 출력을 얻을 수 있습니다.

Today at 18:34:45
Yesterday at 12:30:00
Tomorrow at 09:04:05

2

이것은 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"));

이 코드를 본인 측이나 참조에서 테스트 했습니까?
androidXP

1
    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";

0

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


예, 데이터베이스에 시간을 저장합니다. 하지만 저장된 시간이 오늘인지 어제인지 어제인지 확인해야합니다.
Manikandan

시간을 저장하고 있다면 왜 그가 날짜를 저장할 수 없습니까?
Goofy

그래, 난 할 수 있지만, 내가 좋아하는 그 텍스트 뷰에서 "오늘 8시"와 같은 표시해야합니다
Manikandan

U 할 수 있습니다 ... Db에서 날짜를 가져와 오늘 날짜와 비교합니다. 일치하면 텍스트보기를 "오늘"로 표시합니다 (현재 날짜 인 경우-이전 날짜) "어제"
Goofy


0

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를 제출 했습니다.


0

이것은 내가 지금까지 끝낸 코드입니다.

import android.text.format.DateFormat

fun java.util.Date.asPrettyTime(context: Context): String {
    val nowTime = Calendar.getInstance()

    val dateTime = Calendar.getInstance().also { calendar ->
        calendar.timeInMillis = this.time
    }

    if (dateTime[Calendar.YEAR] != nowTime[Calendar.YEAR]) { // different year
        return DateFormat.format("MM.dd.yyyy.  ·  HH:mm", dateTime).toString()
    }

    if (dateTime[Calendar.MONTH] != nowTime[Calendar.MONTH]) { // different month
        return DateFormat.format("MM.dd.  ·  HH:mm", dateTime).toString()
    }

    return when {
        nowTime[Calendar.DATE] == dateTime[Calendar.DATE] -> { // today
            "${context.getString(R.string.today)}  ·  ${DateFormat.format("HH:mm", dateTime)}"
        }
        nowTime[Calendar.DATE] - dateTime[Calendar.DATE] == 1 -> { // yesterday
            "${context.getString(R.string.yesterday)}  ·  ${DateFormat.format("HH:mm", dateTime)}"
        }
        nowTime[Calendar.DATE] - dateTime[Calendar.DATE] == -1 -> { // tomorrow
            "${context.getString(R.string.tomorrow)}  ·  ${DateFormat.format("HH:mm", dateTime)}"
        }
        else -> { // other date this month
            DateFormat.format("MM.dd.  ·  HH:mm", dateTime).toString()
        }
    }
}

0

다음은 내가 사용하는 간단한 솔루션입니다.

public static boolean isTomorrow(Calendar c) {
    Calendar tomorrow = Calendar.getInstance();
    tomorrow.add(Calendar.DATE,1);
    return (tomorrow.get(Calendar.YEAR) == c.get(Calendar.YEAR)) && (tomorrow.get(Calendar.DAY_OF_YEAR) == (c.get(Calendar.DAY_OF_YEAR)));
}

public static boolean isToday(Calendar c) {
    Calendar today = Calendar.getInstance();
    return (today.get(Calendar.YEAR) == c.get(Calendar.YEAR)) && (today.get(Calendar.DAY_OF_YEAR) == c.get(Calendar.DAY_OF_YEAR));
}

이것은 발생할 수있는 모든 엣지 케이스를 다룹니다.


-1

라이브러리와 간단한 코드없이 모든 Kotlin 프로젝트에서 작업

//Simple date format of the day
val sdfDate = SimpleDateFormat("dd/MM/yyyy")

//Create this 2 extensions of Date
fun Date.isToday() = sdfDate.format(this) == sdfDate.format(Date())
fun Date.isYesterday() =
    sdfDate.format(this) == sdfDate.format(Calendar.getInstance().apply { 
          add(Calendar.DAY_OF_MONTH, -1) }.time)
 
    
//And after everwhere in your code you can do
if(myDate.isToday()){
   ...
}
else if(myDate.isYesterday()) {
...
}

제공된 답변은 검토를 위해 저품질 게시물로 표시되었습니다. 다음은 좋은 답변을 작성하는 방법에 대한 몇 가지 지침입니다 . . 이 제공된 답변은 설명에서 도움이 될 수 있습니다. 코드 전용 답변은 "좋은"답변으로 간주되지 않습니다. 에서 검토 .
Trenton McKinney
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.