Calculate relative time in C#

后端 未结 30 3105
生来不讨喜
生来不讨喜 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:11

    Is there an easy way to do this in Java? The java.util.Date class seems rather limited.

    Here is my quick and dirty Java solution:

    import java.util.Date;
    import javax.management.timer.Timer;
    
    String getRelativeDate(Date date) {     
      long delta = new Date().getTime() - date.getTime();
      if (delta < 1L * Timer.ONE_MINUTE) {
        return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta) + " seconds ago";
      }
      if (delta < 2L * Timer.ONE_MINUTE) {
        return "a minute ago";
      }
      if (delta < 45L * Timer.ONE_MINUTE) {
        return toMinutes(delta) + " minutes ago";
      }
      if (delta < 90L * Timer.ONE_MINUTE) {
        return "an hour ago";
      }
      if (delta < 24L * Timer.ONE_HOUR) {
        return toHours(delta) + " hours ago";
      }
      if (delta < 48L * Timer.ONE_HOUR) {
        return "yesterday";
      }
      if (delta < 30L * Timer.ONE_DAY) {
        return toDays(delta) + " days ago";
      }
      if (delta < 12L * 4L * Timer.ONE_WEEK) { // a month
        long months = toMonths(delta); 
        return months <= 1 ? "one month ago" : months + " months ago";
      }
      else {
        long years = toYears(delta);
        return years <= 1 ? "one year ago" : years + " years ago";
      }
    }
    
    private long toSeconds(long date) {
      return date / 1000L;
    }
    
    private long toMinutes(long date) {
      return toSeconds(date) / 60L;
    }
    
    private long toHours(long date) {
      return toMinutes(date) / 60L;
    }
    
    private long toDays(long date) {
      return toHours(date) / 24L;
    }
    
    private long toMonths(long date) {
      return toDays(date) / 30L;
    }
    
    private long toYears(long date) {
      return toMonths(date) / 365L;
    }
    

提交回复
热议问题