我有一篇文章的发表日期,但需要了解它相对于当前时间的发表时间。
因此,如果文章是在上午 8 点 45 分发布的,并且是在同一天上午 9 点 45 分,我需要能够拥有一个 UILabel,上面写着“1 小时前”。
目前,我正在将日期格式化为“2013 年 5 月 5 日下午 5:35”这样的日期:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Feed *feedLocal = [headlinesArray objectAtIndex:indexPath.row];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MMMM d, yyyy h:mma"];
NSString *dateString = [df stringFromDate:feedLocal.published];
cell.publishedLabel.text = dateString;
}
我怎么能把它转换成“1小时前”这样的东西?谢谢!
编辑
这是我必须至少获得时间的当前方法:
-(NSString *)timeAgo {
NSDate *todayDate = [NSDate date];
double ti = [self timeIntervalSinceDate:todayDate];
ti = ti * -1;
if (ti < 1) {
return @"1s";
} else if (ti < 60) {
return @"1m";
} else if (ti < 3600) {
int diff = round(ti / 60);
return [NSString stringWithFormat:@"%dm", diff];
} else if (ti < 86400) {
int diff = round(ti / 60 / 60);
return[NSString stringWithFormat:@"%dh", diff];
} else if (ti < 2629743) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:@"%dd", diff];
} else if (ti < 31556926) {
int diff = round(ti / 60 / 60 / 24 / 30);
return [NSString stringWithFormat:@"%dmo", diff];
} else {
int diff = round(ti / 60 / 60 / 24 / 30 / 12);
return [NSString stringWithFormat:@"%dy", diff];
}
}