加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Android:如何从服务器日期开始构建日期

发布时间:2020-12-15 02:15:36 所属栏目:Java 来源:网络整理
导读:我有以下代码将服务器返回的日期字符串转换为自字符串. /*** Change date format to "since" string* */public static String timeSince(String dateString) { Date date = stringToDate(dateString); String result = (DateUtils.getRelativeTimeSpanString
我有以下代码将服务器返回的日期字符串转换为自字符串.

/**
* Change date format to "since" string
* */
public static String timeSince(String dateString) {
    Date date = stringToDate(dateString);
    String result = (DateUtils.getRelativeTimeSpanString(date.getTime())).toString();
    return result;
}
/**
 * Function to convert server date string to Date
 * */
public static Date stringToDate(String s){
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    try {
        return df.parse(s);
    } catch(ParseException e){
        e.printStackTrace();
    }
    return null;
}

但是,作为一个例子,如果我打电话
timeSince(“2016-07-04T07:21:39.575Z”)我得到了“2016年7月4日”,而不是“3天前”或任何其他相对于现在的时期.知道为什么吗?谢谢…

解决方法

好.事实证明,DateUtils.getRelativeTimeSpanString(date.getTime())返回RELATIVE持续时间(例如“昨天”或“30分钟前”)除非持续时间大于一周,在这种情况下它返回ABSOLUTE(查看代码)日期…… 文档中没有任何内容如此说明……但这是事实.大多数Android解决方案的另一个缺点是消息没有本地化(“3分钟前”在法语,西班牙语或其他任何语言中都不起作用).所以我可能最终会为此编写自己的库. 最重要的是,如果您使用英语并希望将日期显示为绝对日期(如果它超过一周前),则上述代码有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读