Calculate relative time in C#

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

    iPhone Objective-C Version

    + (NSString *)timeAgoString:(NSDate *)date {
        int delta = -(int)[date timeIntervalSinceNow];
    
        if (delta < 60)
        {
            return delta == 1 ? @"one second ago" : [NSString stringWithFormat:@"%i seconds ago", delta];
        }
        if (delta < 120)
        {
            return @"a minute ago";
        }
        if (delta < 2700)
        {
            return [NSString stringWithFormat:@"%i minutes ago", delta/60];
        }
        if (delta < 5400)
        {
            return @"an hour ago";
        }
        if (delta < 24 * 3600)
        {
            return [NSString stringWithFormat:@"%i hours ago", delta/3600];
        }
        if (delta < 48 * 3600)
        {
            return @"yesterday";
        }
        if (delta < 30 * 24 * 3600)
        {
            return [NSString stringWithFormat:@"%i days ago", delta/(24*3600)];
        }
        if (delta < 12 * 30 * 24 * 3600)
        {
            int months = delta/(30*24*3600);
            return months <= 1 ? @"one month ago" : [NSString stringWithFormat:@"%i months ago", months];
        }
        else
        {
            int years = delta/(12*30*24*3600);
            return years <= 1 ? @"one year ago" : [NSString stringWithFormat:@"%i years ago", years];
        }
    }
    

提交回复
热议问题