Calculate relative time in C#

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

    I would provide some handy extensions methods for this and make the code more readable. First, couple of extension methods for Int32.

    public static class TimeSpanExtensions {
    
        public static TimeSpan Days(this int value) {
    
            return new TimeSpan(value, 0, 0, 0);
        }
    
        public static TimeSpan Hours(this int value) {
    
            return new TimeSpan(0, value, 0, 0);
        }
    
        public static TimeSpan Minutes(this int value) {
    
            return new TimeSpan(0, 0, value, 0);
        }
    
        public static TimeSpan Seconds(this int value) {
    
            return new TimeSpan(0, 0, 0, value);
        }
    
        public static TimeSpan Milliseconds(this int value) {
    
            return new TimeSpan(0, 0, 0, 0, value);
        }
    
        public static DateTime Ago(this TimeSpan value) {
    
            return DateTime.Now - value;
        }
    }
    

    Then, one for DateTime.

    public static class DateTimeExtensions {
    
        public static DateTime Ago(this DateTime dateTime, TimeSpan delta) {
    
            return dateTime - delta;
        }
    }
    

    Now, you can do something like below:

    var date = DateTime.Now;
    date.Ago(2.Days()); // 2 days ago
    date.Ago(7.Hours()); // 7 hours ago
    date.Ago(567.Milliseconds()); // 567 milliseconds ago
    

提交回复
热议问题