Best way to format a date relative to now on Android

前端 未结 10 1715
隐瞒了意图╮
隐瞒了意图╮ 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

    build.gradle

    compile 'joda-time:joda-time:2.9.9'
    

    Utils.java

    private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd, yyyy");
        private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat(" 'at' h:mm aa");
        public static String getRelativeDateTimeString(Calendar startDateCalendar) {
            if (startDateCalendar == null) return null;
    
            DateTime startDate = new DateTime(startDateCalendar.getTimeInMillis());
            DateTime today = new DateTime();
            int days = Days.daysBetween(today.withTimeAtStartOfDay(), startDate.withTimeAtStartOfDay()).getDays();
    
            String date;
            switch (days) {
                case -1: date = "Yesterday"; break;
                case 0: date = "Today"; break;
                case 1: date = "Tomorrow"; break;
                default: date = DATE_FORMAT.format(startDateCalendar.getTime()); break;
            }
            String time = TIME_FORMAT.format(startDateCalendar.getTime());
            return date + time;
        }
    

    Output

    Yesterday at 9:52 AM
    Today at 9:52 AM
    Tomorrow at 9:52 AM
    Sep 05, 2017 at 9:52 AM
    

提交回复
热议问题