Calculate relative time in C#

后端 未结 30 2114
生来不讨喜
生来不讨喜 2020-11-21 05:59

Given a specific DateTime value, how do I display relative time, like:

  • 2 hours ago
  • 3 days ago
  • a month ago
30条回答
  •  [愿得一人]
    2020-11-21 06:30

    /** 
     * {@code date1} has to be earlier than {@code date2}.
     */
    public static String relativize(Date date1, Date date2) {
        assert date2.getTime() >= date1.getTime();
    
        long duration = date2.getTime() - date1.getTime();
        long converted;
    
        if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) {
            return String.format("%d %s ago", converted, converted == 1 ? "day" : "days");
        } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) {
            return String.format("%d %s ago", converted, converted == 1 ? "hour" : "hours");
        } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) {
            return String.format("%d %s ago", converted, converted == 1 ? "minute" : "minutes");
        } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) {
            return String.format("%d %s ago", converted, converted == 1 ? "second" : "seconds");
        } else {
            return "just now";
        }
    }
    

提交回复
热议问题