-(NSString*)timeAgoFor:(NSString*)tipping_date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:tipping_date];
NSString *key = @"";
NSTimeInterval ti = [date timeIntervalSinceDate:[NSDate date]];
key = (ti > 0) ? @"Left" : @"Ago";
ti = ABS(ti);
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:date];
if (result == NSOrderedSame) {
return[NSString stringWithFormat:@"Today"];
}
else if (ti < 86400 * 2) {
return[NSString stringWithFormat:@"1 Day %@",key];
}else if (ti < 86400 * 7) {
int diff = round(ti/60/60/24);
return[NSString stringWithFormat:@"%d Days %@", diff,key];
}else {
int diff = round(ti/(86400 * 7));
return[NSString stringWithFormat:@"%d Wks %@", diff,key];
}
}
nên có sự ngắt sau mỗi câu lệnh để không nhập vào các trường hợp khác. –
Lưu ý rằng điều này sẽ không bao giờ trở lại "ngày hôm nay" - NSDate đại diện cho một thời điểm cụ thể, do đó, 'NSOrderedSame' sẽ (về cơ bản) không bao giờ xảy ra – Tim