【问题标题】:How to find time is today or yesterday in android如何在android中找到今天或昨天的时间
【发布时间】:2012-10-10 11:55:21
【问题描述】:

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

【问题讨论】:

  • 请显示您已完成的代码...
  • @Keyser 你能告诉我怎么做吗?
  • 由于您还没有尝试过任何代码,所以您不知道需要什么帮助。问一个问题还为时过早。等到你看到什么给你带来麻烦。
  • 当你从数据库中取数据时,取最后一次在发送箱中的转换时间
  • @user1498488 简单地找一些Java日期/时间处理的教程。

标签: android time


【解决方案1】:

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

DateUtils.isToday(long timeInMilliseconds)

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

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

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

DateUtils

【讨论】:

  • DateUtils.isToday(myDate.getTime()) 工作正常,谢谢!
  • 这是消耗本地(非 UTC)时间还是仅消耗 UTC 时间戳?
  • DateUtils.isToday(long millis) 按照@Maragues 的描述工作,但请注意,如果您在要进行单元测试的一段代码(如 ViewModel 或 Presenter)中使用此方法,您将运行测试时获得 RuntimeException。这是因为用于单元测试的 android.jar 不包含任何代码。欲了解更多信息link
  • 昨天 24 小时后,但我想在 1 天前得到这个,请指导我
【解决方案2】:

如前所述,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 或任何你喜欢的类一起使用。
  • 这很棒。但由于某些奇怪的原因,我无法将其用作 Kotlin 中的扩展功能,例如:fun DateUtils.isYesterday(d: Long): Boolean { return DateUtils.isToday(d + DateUtils.DAY_IN_MILLIS) }
  • 我认为这是最好的解决方案,只需两行代码即可完成工作
【解决方案3】:

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

【讨论】:

  • 你确定它是正确的吗?你只比较日期,那么年份和月份呢?今天是 2014 年 11 月 20 日,但您的代码显示 2010 年 10 月 20 日的“今天”
  • 这个答案不正确。根据文档,Calendar.DATE 是 DAY_OF_MONTH 的同义词。因此,您既不比较年份也不比较月份。
  • 是的,这是不正确的。 (Calendar.DATE) == smsTime.get(Calendar.DATE) 只匹配日期,而不是月份和年份。它为 01.01.2012 和 01.01.2017 返回 true
  • 对于“今天”文本,此解决方案始终正确,但对于“昨天”文本,该解决方案在该月的第一天不正确。方法 get(Calendar.DATE) 返回一个月中的某一天,例如 1 - 31 = -30 而不是 1 应该显示“昨天”的内容 - 因为 12 月 31 日是 1 月 1 日的前一天。
  • “今天”和“昨天”需要在支票中包括月份和年份,而不仅仅是 Calendar.DATE
【解决方案4】:

今天您可以使用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 完美!
  • 上面带有 now.get(Calendar.MONTH) 的代码似乎返回了上个月!?
  • @tina 它应该只发生在每月的第一天
【解决方案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();
    }
}

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

【讨论】:

  • 嗨!感谢它真正有帮助的代码!它只是有一个小问题,“昨天在”和“明天在”的条件是相同的!“明天在”应该是 -1
【解决方案6】:

你可以试试这个:

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

    【讨论】:

      【解决方案8】:

      另一种方法。在 kotlin 中使用推荐的 lib 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())
        

      【讨论】:

      • 这应该是要走的路。自定义解析很糟糕。
      【解决方案9】:

      科特林

      @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
      

      【讨论】:

        【解决方案10】:

        这是获取今天、昨天和日期等值的方法,例如 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"));
        

        【讨论】:

        • 您是否在您身边测试过这段代码或任何参考?
        【解决方案11】:

        使用 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")
        }
        

        【讨论】:

          【解决方案12】:
              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";
          

          【讨论】:

            【解决方案13】:

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

            【讨论】:

            【解决方案14】:

            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,去投票吧

            【讨论】:

              【解决方案15】:

              这是我现在最终得到的代码:

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

              【讨论】:

                【解决方案16】:

                这是我使用的一个简单解决方案:

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

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

                【讨论】:

                  【解决方案17】:

                  无需任何库和简单代码,即可处理每个 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()) {
                  ...
                  }
                  

                  【讨论】:

                  • 所提供的答案被标记为低质量帖子以供审核。以下是How do I write a good answer? 的一些指南。这个提供的答案可以从解释中受益。仅代码答案不被视为“好”答案。来自Review
                  猜你喜欢
                  • 1970-01-01
                  • 2011-05-02
                  • 2012-03-12
                  • 2011-06-14
                  • 2014-05-25
                  • 1970-01-01
                  • 1970-01-01
                  • 2016-05-28
                  • 1970-01-01
                  相关资源
                  最近更新 更多