iPhone: Convert date string to a relative time stamp

后端 未结 11 1142
醉梦人生
醉梦人生 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

    -(NSString *)dateDiff:(NSString *)origDate {
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setFormatterBehavior:NSDateFormatterBehavior10_4];
        [df setDateFormat:@"EEE, dd MMM yy HH:mm:ss VVVV"];
        NSDate *convertedDate = [df dateFromString:origDate];
        [df release];
        NSDate *todayDate = [NSDate date];
        double ti = [convertedDate timeIntervalSinceDate:todayDate];
        ti = ti * -1;
        if(ti < 1) {
            return @"never";
        } else  if (ti < 60) {
            return @"less than a minute ago";
        } else if (ti < 3600) {
            int diff = round(ti / 60);
            return [NSString stringWithFormat:@"%d minutes ago", diff];
        } else if (ti < 86400) {
            int diff = round(ti / 60 / 60);
            return[NSString stringWithFormat:@"%d hours ago", diff];
        } else if (ti < 2629743) {
            int diff = round(ti / 60 / 60 / 24);
            return[NSString stringWithFormat:@"%d days ago", diff];
        } else {
            return @"never";
        }   
    }
    

提交回复
热议问题