0

我有一篇文章的发表日期,但需要了解它相对于当前时间的发表时间。

因此,如果文章是在上午 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];
    }
}
4

1 回答 1

1

我不确定 timeAgo 是什么方法,但这里有一个解决方案,假设它与 tableView:cellForRowAtIndexPath 在同一个 viewController 中。如果你能澄清它的一种方法,我可以修改它并为你提供更多帮助。

首先更改 timeAgo 以获取日期并对其进行比较。

-(NSString *)timeSincePublished:(NSDate *)publicationDate 
{
    double ti = [publicationDate timeIntervalSinceNow];

上述方法中的其他所有内容都应相同。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Feed *feedLocal = [headlinesArray objectAtIndex:indexPath.row];
    NSString *dateString = [self timeSincePublished:feedLocal.published];
    cell.publishedLabel.text = dateString;
}
于 2013-05-10T02:20:01.763 回答