我所拥有的只是NSTimeInterval
过去。如何将其转换为“ humanly readable
”字符串,如“ 10 seconds ago
”或“ 3 hours ago
”?
问问题
200 次
2 回答
2
NSTimeInterval 给你几秒钟。
确认秒数后,您可以使用 % 和 / 来查找天、小时、分钟和秒。
看这个演示:
NSInteger seconds = totalSecondsSinceStart % 60;
NSInteger minutes = (totalSecondsSinceStart / 60) % 60;
NSInteger hours = totalSecondsSinceStart / (60 * 60);
NSString *result = NSString stringWithFormat:@"%02ld hour %02ld minutues %02ld seconds ago", hours, minutes, seconds];
输出将如下所示:
01 hours 34 minutes 49 seconds ago
于 2013-01-16T13:04:27.593 回答
0
更多格式,因此您看不到 0 小时 0 分 34 秒。
+(NSString *)returnRelativeTime:(NSString *)dateString
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [formatter dateFromString:dateString];
int timeSince = [date timeIntervalSinceNow] * -1;
int days = (timeSince / (3600 * 24));
int hours = (timeSince / 3600)- (days *24);
int minutes = (timeSince % 3600) / 60;
// int seconds = (timeSince % 3600) % 60;
// return [NSString stringWithFormat:@"%02d:%02d:%02d",hours ,minutes, seconds];
if (days >0) {
return [NSString stringWithFormat:@"%01d days %01d hours ago",days, hours];
}
else if (hours == 0) {
return [NSString stringWithFormat:@"%01dm ago", minutes];
}
else {
return [NSString stringWithFormat:@"%01dh %01dm ago", hours ,minutes];
}
}
于 2013-01-16T13:58:14.717 回答