ios - 在 Objective C 中获取两个 NSString 之间的时间差

标签 ios objective-c nsstring nsdate

我有两个字符串来 self 存储时间的服务器,我需要比较这两个字符串之间的时间间隔,以分钟为单位,如果有必要,以小时为单位。我应该转换为 NSDate 还是使用 NSString

NSString 看起来像:

NOW 14:22
LAST TIME 10:18

编辑 #1 由于每个人都在说我使用 NSDate,我将数据库中的数据转换为 DATETIME,现在我可以使用以下代码比较两个 NSDate:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"pt_BR"]];
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];

    NSDate *currentDateTimeWithOffset = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];

    NSString *strDate = [dateFormatter stringFromDate:currentDateTimeWithOffset];
    NSDate * now = [dateFormatter dateFromString:strDate];
NSDate *date = [dateFormatter dateFromString:@"2013-04-09 12:10:18"];

NSLog(@"Difference %f",[now timeIntervalSinceDate:date]);

结果如下:

 Difference 864.000000
 NOW 2013-04-09 15:24:42 +0000
 LAST DATE 2013-04-09 12:10:18

这样对吗?区别在于秒数?

最佳答案

如果格式变得比您显示的更复杂,请考虑使用 NSDateFormatter。对于简单的例子:

NSArray *hoursMins = [timeString componentsSeparatedByString:@":"];
NSInteger timeInMins = [hoursMins[0] intValue] * 60 + [hoursMins[1] intValue];

然后以分钟为单位减去两次。日期格式化程序方法如下所示:

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"HH:mm"];
NSDate *date = [df dateFromString:timeString];

您可以使用以下方法获得两个日期之间的秒数差异:

[date timerIntervalSinceDate:anotherDate];

关于ios - 在 Objective C 中获取两个 NSString 之间的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15908605/

相关文章:

ios - 在 iOS 上打开与 Icecast 服务器的套接字连接

ios - 获取drawRect中UISlider的当前值 : method

ios - NSString 保留计数 -1

ios - Objective-C 中的字符串替换

objective-c - 如何在一个容器中制作两个文本字段?

iphone - iPhone 上 NSString 的 AES 加密

ios - 查看已失效的 iPhone 应用程序的代码

ios - 与 iPad 集成表格 View 应用程序

ios - Swift - 初始化 UITableViewCell

Objective-C 属性访问