Best way to format a date relative to now on Android

前端 未结 10 1714
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 15:57

I am creating a feature in an Android app to get an arbitrary date (past, present or future) and find the difference relative to now.

Both my now and

10条回答
  •  一向
    一向 (楼主)
    2021-01-31 16:43

    I came here for an alternative but I can't find perfect rather than my code. So I shared here any improvements are welcome.

    public String getCreatedAtRelative() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
        df.setTimeZone(TimeZone.getTimeZone("IST"));
        CharSequence relative = null;
        try {
            relative = DateUtils.getRelativeTimeSpanString(df.parse(createdAt).getTime(), new Date().getTime(),
                    0L, DateUtils.FORMAT_ABBREV_ALL);
        } catch (ParseException e) {
            Log.e("Parse Exception adapter", "created at", e);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        if (null == relative) {
            return createdAt;
        } else {
            return relative.toString().replace(".", " ");
        }
    }
    

提交回复
热议问题