iPhone:将日期字符串转换为相对时间戳

标签 iphone objective-c cocoa datetime time

我有一个像这样的字符串的时间戳:

Thu, 21 May 09 19:10:09 -0700

我想将其转换为相对时间戳,例如“20 分钟前”或“3 天前”。

在 iPhone 上使用 Objective-C 的最佳方法是什么?

最佳答案

-(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:将日期字符串转换为相对时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/902950/

相关文章:

iphone - 在 iPhone map 中的 route 添加注释

ios - 关于在 Swift 中采用 Objective-C 协议(protocol)的困惑

swift - NSDateComponentsFormatter 省略了单位。为什么?

ios - Swift4 tableview 单元格高度不是动态的并且始终是静态的

iphone - NSString 的问题

ios - 将 AVPlayerViewController.player 设置为 nil 会破坏隐藏式字幕

Cocoa:创建可拖动区域

cocoa - 如何关闭窗口(卸载 NIB)?

iphone - NSRunLoop 和 GCD 队列

iphone - 我们如何保存多个具有不同音频数据(声音)和不同名称的音频录制文件(.caf)?