【问题标题】:Google Hangouts like "ago" timespan谷歌环聊喜欢“以前”的时间跨度
【发布时间】:2015-10-24 04:56:33
【问题描述】:

我一直在尝试使用

DateUtils.getRelativeTimeSpanString()

...生成与 Google Hangouts 应用程序类似的经过时间字符串。

但是,我得到的字符串如下:

1 min ago
58 min ago
10 hours ago
yesterday
3 days ago
1 week ago 

环聊应用显示如下字符串:

Now
58 min ago
11:05     (if time is more than 1 hour ago, it'll show the original time)
yesterday
Wed       (if the day was more than 1 day ago, it'll show the day)
July 21   (if more than 1 wee ago, it'll show the date)

我正在寻找类似环聊的格式。

只是好奇我是否在此方法中使用了错误的标志,或者环聊应用是否使用不同的方法/库来生成时间跨度字符串。如果 DateUtils 没有提供我正在寻找的内容,我可以进行自定义实现。

【问题讨论】:

  • 你的问题不清楚。如果要显示日期时间,只需使用格式化程序创建日期时间的字符串表示,同时完全避免相对时间类。也许您可以编辑您的问题以澄清并发布更多您想要的示例。
  • 我添加了一个更清晰的例子来说明 DateUtils.geRelativeTimeSpanString();返回时间跨度字符串与 hangots 应用程序如何显示时间跨度字符串。

标签: android html date time


【解决方案1】:

我最终组合了不同的 DateUtils 格式化程序:

@SuppressLint("SimpleDateFormat")
public static String getTimeSpanString(Context mContext, long time, boolean showTime) {

    int flags = DateUtils.FORMAT_ABBREV_RELATIVE | DateUtils.FORMAT_ABBREV_ALL;

    if(showTime) {
        flags |= DateUtils.FORMAT_SHOW_TIME;
    }

    long now = new Date().getTime();
    long duration = now - time;

    if(duration < DateUtils.HOUR_IN_MILLIS) {
        return DateUtils.getRelativeTimeSpanString(time, now, 0, flags).toString();
    } else if (DateUtils.isToday(time)) {
        SimpleDateFormat timeInstance;
        if(DateFormat.is24HourFormat(mContext)) {
            timeInstance = new SimpleDateFormat("HH:mm");
        } else {
            timeInstance = new SimpleDateFormat("hh:mm a");
        }

        return timeInstance.format(time);
    } else if (duration < DateUtils.WEEK_IN_MILLIS) {
        return DateUtils.formatDateTime(mContext,time,flags | DateUtils.FORMAT_SHOW_WEEKDAY);
    }

    return DateUtils.formatDateTime(mContext, time, flags | DateUtils.FORMAT_SHOW_DATE);
}

【讨论】:

    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多