问题描述
我有一个如下字符串的时间戳:
,我想将其转换为相对时间戳,例如'20分钟前'或'3天前'。
使用Objective-C for iPhone的最好方法是什么?
pre> - (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 return @less than a minute ago;
} else if(ti int diff = round(ti / 60);
return [NSString stringWithFormat:@%d minutes ago,diff];
} else if(ti int diff = round(ti / 60/60);
return [NSString stringWithFormat:@%d hours ago,diff];
} else if(ti int diff = round(ti / 60/60/24);
return [NSString stringWithFormat:@%d days ago,diff];
} else {
return @never;
}
}
I've got a timestamp as a string like:
and I'd like to convert it to a relative time stamp like '20 minutes ago' or '3 days ago'.
What's the best way to do this using Objective-C for the iPhone?
-(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";
}
}
这篇关于iPhone:将日期字符串转换为相对时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!