【问题标题】:DateUtils.getRelativeTimeSpanString for future dates未来日期的 DateUtils.getRelativeTimeSpanString
【发布时间】:2013-03-05 04:57:20
【问题描述】:

因此,Android SDK 中的 [DateUtils.getRelativeTimeSpanString()][1] 非常适合显示过去的相对时间。

即:5 天前,或 5 分钟前。

但对于未来的日期似乎不太适用。它似乎只是打印日期。

是否有任何简单的替代方法可以为将来的日期生成相对时间跨度字符串(缺少通过比较两个日历对象来计算天、小时、分钟、秒的东西)?

排长队:5 天后,还是 5 分钟后?

这基本上是我要做的,它只是看起来有点脏(注意:这段代码只是为帖子编写的,实际上并没有通过 java 编译器运行):

Calendar calendarIO = Calendar.getInstance();
calendarIO.set(2013, 2, 14, 7, 0);

long milliseconds1 = calendarIO.getTimeInMillis();
long milliseconds2 = System.currentTimeMillis();
long diff = milliseconds1 - milliseconds2;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);   

String relativeTime = "";
if (diffDays > 1) {
    relativeTime = diffDays + " days";
} else if (diffDays > 0) {
    relativeTime = diffDays + " days " + diffHours + " hours";
} else if (diffHours > 1) {
    relativeTime = diffHours + " hours";
} else if (diffMinutes > 0) {
    relativeTime = diffMinutes + " minutes.";
}

【问题讨论】:

    标签: android


    【解决方案1】:

    我会尝试使用DateUtils.getRelativeTimeSpanString(time, now, minResolution),因为它适用于使用“n 天”格式的未来日期。

    http://developer.android.com/reference/android/text/format/DateUtils.html#getRelativeTimeSpanString

    【讨论】:

      【解决方案2】:

      按照以下步骤进行

      String dateString = "06/05/2019 06:49:00 AM";
      
      SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
      
       Date convertedDate = new Date();
      try {
            convertedDate = dateFormat.parse(dateString);
            long cuMillis = System.currentTimeMillis();
      
            String timeAgo = (String) DateUtils.getRelativeTimeSpanString(convertedDate.getTime(), cuMillis, 1, FORMAT_ABBREV_RELATIVE);
      
            Log.d("LOG", "Time Ago==>" + timeAgo);
      
         } catch (ParseException e) {
      
          e.printStackTrace();
        } 
      

      【讨论】:

        【解决方案3】:
        DateUtils.getRelativeTimeSpanString(endDate.getTime(), startDate.getTime(), DateUtils.FORMAT_ABBREV_RELATIVE);
        

        需要注意以下几点:

        明天而不是 1 天。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-02
          • 1970-01-01
          • 2020-05-10
          相关资源
          最近更新 更多