iPhone: Convert date string to a relative time stamp

后端 未结 11 1097
醉梦人生
醉梦人生 2020-11-27 09:30

I\'ve got a timestamp as a string like:

Thu, 21 May 09 19:10:09 -0700

and I\'d like to convert it to a relative time stamp like

11条回答
  •  离开以前
    2020-11-27 10:10

    I took Carl Coryell-Martin's code and made a simpler NSDate category that doesn't have warnings about the string formatting of the singulars, and also tidys up the week ago singular:

    @interface NSDate (Extras)
    - (NSString *)differenceString;
    @end
    
    @implementation NSDate (Extras)
    
    - (NSString *)differenceString{
        NSDate* date = self;
        NSDate *now = [NSDate date];
        double time = [date timeIntervalSinceDate:now];
        time *= -1;
        if (time < 60) {
            int diff = round(time);
            if (diff == 1)
                return @"1 second ago";
            return [NSString stringWithFormat:@"%d seconds ago", diff];
        } else if (time < 3600) {
            int diff = round(time / 60);
            if (diff == 1)
                return @"1 minute ago";
            return [NSString stringWithFormat:@"%d minutes ago", diff];
        } else if (time < 86400) {
            int diff = round(time / 60 / 60);
            if (diff == 1)
                return @"1 hour ago";
            return [NSString stringWithFormat:@"%d hours ago", diff];
        } else if (time < 604800) {
            int diff = round(time / 60 / 60 / 24);
            if (diff == 1)
                return @"yesterday";
            if (diff == 7)
                return @"a week ago";
            return[NSString stringWithFormat:@"%d days ago", diff];
        } else {
            int diff = round(time / 60 / 60 / 24 / 7);
            if (diff == 1)
                return @"a week ago";
            return [NSString stringWithFormat:@"%d weeks ago", diff];
        }   
    }
    
    @end
    

提交回复
热议问题