如何在android中查找时间是今天还是昨天

问题描述 投票:0回答:20

我正在开发一个用于发送短信的应用程序。我通过从数据库检索时间来存储当前时间并显示在发送的历史记录页面中。在发送历史记录页面中,我想显示消息发送的时间。这里我想检查一下消息是今天发送的还是昨天发送的还是前天发送的。如果消息是昨天发送的,则意味着我需要像这样显示“昨天 20:00”,甚至消息是昨天发送的,意味着“星期一 20:00”。我不知道该怎么做。如果有人知道请帮助我。

android time
20个回答
278
投票

要检查日期是否是今天,请使用 Android utils 库

DateUtils.isToday(long timeInMilliseconds)

这个 utils 类还提供人类可读的相对时间字符串。例如,

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

您可以使用几个参数来定义时间跨度的精确度

参见 DateUtils


110
投票

如前所述,

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

55
投票

您可以使用 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 以进一步了解。


22
投票

今天您可以使用

android API
中的 DateUtils.isToday

昨天您可以使用该代码:

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

13
投票

未使用任何库


昨天

今天

明天

今年

任何年份

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

Kotlin 扩展功能:

fun Long.toPrettyDate(): String {
    val nowTime = Calendar.getInstance()
    val neededTime = Calendar.getInstance()
    neededTime.timeInMillis = this
    
    return if (neededTime[Calendar.YEAR] == nowTime[Calendar.YEAR]) {
        if (neededTime[Calendar.MONTH] == nowTime[Calendar.MONTH]) {
            when {
                neededTime[Calendar.DATE] - nowTime[Calendar.DATE] == 1 -> {
                    //here return like "Tomorrow at 12:00"
                    "Tomorrow at " +  SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(this))
                }
                nowTime[Calendar.DATE] == neededTime[Calendar.DATE] -> {
                    //here return like "Today at 12:00"
                    "Today at " +  SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(this))
                }
                nowTime[Calendar.DATE] - neededTime[Calendar.DATE] == 1 -> {
                    //here return like "Yesterday at 12:00"
                    "Yesterday at " +  SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(this))
                }
                else -> {
                    //here return like "May 31, 12:00"
                    SimpleDateFormat("MMMM d, HH:mm", Locale.getDefault()).format(Date(this))
                }
            }
        } else {
            //here return like "May 31, 12:00"
            SimpleDateFormat("MMMM d, HH:mm", Locale.getDefault()).format(Date(this))
        }
    } else {
        //here return like "May 31 2022, 12:00" - it's a different year we need to show it
        SimpleDateFormat("MMMM dd yyyy, HH:mm", Locale.getDefault()).format(Date(this))
    }
}

10
投票

如果你的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)
} 

9
投票

你可以试试这个:

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

8
投票

Blow 片段在回收器视图标题部分很有用。

Kotlin 扩展:

fun Date.isYesterday(): Boolean = DateUtils.isToday(this.time + DateUtils.DAY_IN_MILLIS)

fun Date.isToday(): Boolean = DateUtils.isToday(this.time)


fun Date.toDateString(): String {
   return when {
    this.isToday() -> {
        "Today"
    }
    this.isYesterday() -> {
        "Yesterday"
    }
    else -> {
        convetedDate.format(this)
    }
 }
}

5
投票

另一种方法。在 kotlin 中,带有推荐的库 ThreeTen

  1. 添加三十

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

5
投票

科特林

@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

3
投票

用作 kotlin 扩展也相当漂亮:

fun Calendar.isToday() : Boolean {
    val today = Calendar.getInstance()
    return today[Calendar.YEAR] == get(Calendar.YEAR) && today[Calendar.DAY_OF_YEAR] == get(Calendar.DAY_OF_YEAR)
}

并使用:

if (calendar.isToday()) {
    Log.d("Calendar", "isToday")
}

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

使用此方法只需传递毫秒之类的

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

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

1
投票

在 Kotlin 中

结果:

今天的日期 --> 今天

昨天日期 -> 昨天

今年日期 -> 6 月 20 日

不是今年日期 -> 2019 年 2 月 1 日

fun Context.toReadableDateFormat(date: Long, comparableDate: Long = System.currentTimeMillis()): String{
   val comparableDateTime = comparableDate.getCalendar()
   val itemDateTime = date.getCalendar()
   return if(
    comparableDateTime.get(Calendar.DAY_OF_MONTH) == itemDateTime.get(Calendar.DAY_OF_MONTH) &&
    comparableDateTime.get(Calendar.MONTH) == itemDateTime.get(Calendar.MONTH) &&
    comparableDateTime.get(Calendar.YEAR) == itemDateTime.get(Calendar.YEAR)
)
       "Today"
   else if(isYesterday(date).orFalse())
       "Yesterday"
   else if(comparableDateTime.get(Calendar.YEAR) == itemDateTime.get(Calendar.YEAR))
       itemDateTime.toFormat("dd MMM")
   else
       itemDateTime.toFormat("dd MMM yyyy")

}

昨天检查

fun isYesterday(date: Long, comparableDate: Long = System.currentTimeMillis()): Boolean {
   val comparableDateTime = comparableDate.getCalendar()
   val itemDateTime = date.getCalendar()
   comparableDateTime.add(Calendar.DATE, -1)
   return comparableDateTime.get(Calendar.DAY_OF_MONTH) ==
        itemDateTime.get(Calendar.DAY_OF_MONTH) &&
        comparableDateTime.get(Calendar.MONTH) ==
        itemDateTime.get(Calendar.MONTH) &&
        comparableDateTime.get(Calendar.YEAR) ==
        itemDateTime.get(Calendar.YEAR) 
}



fun Long.getCalendar() = Calendar.getInstance().apply {
   timeInMillis = this@getCalendar
}

要调用上述函数,请使用此语法

context.toReadableDateFormat(1687342714503) // your date in timestamp 

0
投票

我可以建议你一件事。当您发送短信时,将详细信息存储到数据库中,以便您可以在历史记录页面中显示短信发送的日期和时间。


0
投票

DateUtils.isToday()
应被视为已弃用,因为
android.text.format.Time
现已弃用。 在他们更新 isToday 的源代码之前,这里没有解决方案可以检测今天、昨天、处理夏令时之间的转换,并且不使用已弃用的代码。这是在 Kotlin 中,使用必须定期保持最新的
today
字段(例如
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));
}

这涵盖了可能发生的所有边缘情况。


0
投票

这是我根据我的需要给出的答案。只是分享以防其他人可能觉得有用。即使昨天或明天分别在不同的月份或年份,我的代码也可以工作。享受吧!

 fun getAppropriateStringFromDueDate(dueDate: Date): String {

    val timeFormatter = SimpleDateFormat("HH:mm")
    val dateFormatter = SimpleDateFormat("EEE, d MMM yyyy HH:mm")
    val time = timeFormatter.format(dueDate)

    val calendar = Calendar.getInstance()
    calendar.time = todayDate
    calendar.set(Calendar.HOUR_OF_DAY, 0)
    calendar.set(Calendar.MINUTE, 0)
    val timeDifference = dueDate.time - calendar.timeInMillis
    val aDayInMillis = DateUtils.DAY_IN_MILLIS
    val twoDaysInMillis = 2 * aDayInMillis
    return when(timeDifference) {
        in 0L..< aDayInMillis -> "Today, $time"
        in aDayInMillis..<twoDaysInMillis ->  "Tomorrow, $time"
        in -aDayInMillis..<0L ->  "Yesterday, $time"
        else -> dateFormatter.format(dueDate)
    }

}

-2
投票

无需任何库和简单代码,即可处理每个 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()) {
...
}
© www.soinside.com 2019 - 2024. All rights reserved.