Calculate relative time in C#

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

    Java for client-side gwt usage:

    import java.util.Date;
    
    public class RelativeDateFormat {
    
     private static final long ONE_MINUTE = 60000L;
     private static final long ONE_HOUR = 3600000L;
     private static final long ONE_DAY = 86400000L;
     private static final long ONE_WEEK = 604800000L;
    
     public static String format(Date date) {
    
      long delta = new Date().getTime() - date.getTime();
      if (delta < 1L * ONE_MINUTE) {
       return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta)
         + " seconds ago";
      }
      if (delta < 2L * ONE_MINUTE) {
       return "one minute ago";
      }
      if (delta < 45L * ONE_MINUTE) {
       return toMinutes(delta) + " minutes ago";
      }
      if (delta < 90L * ONE_MINUTE) {
       return "one hour ago";
      }
      if (delta < 24L * ONE_HOUR) {
       return toHours(delta) + " hours ago";
      }
      if (delta < 48L * ONE_HOUR) {
       return "yesterday";
      }
      if (delta < 30L * ONE_DAY) {
       return toDays(delta) + " days ago";
      }
      if (delta < 12L * 4L * ONE_WEEK) {
       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 static long toSeconds(long date) {
      return date / 1000L;
     }
    
     private static long toMinutes(long date) {
      return toSeconds(date) / 60L;
     }
    
     private static long toHours(long date) {
      return toMinutes(date) / 60L;
     }
    
     private static long toDays(long date) {
      return toHours(date) / 24L;
     }
    
     private static long toMonths(long date) {
      return toDays(date) / 30L;
     }
    
     private static long toYears(long date) {
      return toMonths(date) / 365L;
     }
    
    }
    

提交回复
热议问题