ios - 比较两个相同的 NSDates 返回不平等的结果

标签 ios nsdate

我正在比较两个名为 serverDatelocalDate 的 NSDate。尽管两个日期输出是同一时间,但我继续得到 serverDate 显示为比 localDate 更新。

这是我的比较代码:

if ([serverDate timeIntervalSinceReferenceDate] > [localDate timeIntervalSinceReferenceDate]) {
        NSLog(@"server date more recent");

    } else if ([serverDate timeIntervalSinceReferenceDate] <= [localDate timeIntervalSinceReferenceDate]){
        NSLog(@"local date more recent");

    }

我使用了非常精确的 NSDateFormatter 将日期显示为 "yyyy-MM-dd HH:mm:ss:SSSSSSSSSSZ",输出如下:服务器日期:2014-09-17 23:20:02:5090000000-0700,本地日期:2014-09-17 23:20:02:5090000000-0700。但即便如此,serverDate 仍被视为最近的日期。

我做错了什么?感谢您的输入。

最佳答案

你不应该使用 NSimeIntervell 因为 NSDateCompare 比较日期的函数,而是使用 compare 函数

if ([serverDate  compare:localDate ] == NSOrderedDescending) {
    NSLog(@"serverDate is later than localDate");
} else if ([serverDate  compare:localDate] == NSOrderedAscending) {
    NSLog(@"serverDate is earlier than localDate");
} else {
    NSLog(@"dates are the same");
}

希望对你有帮助

关于ios - 比较两个相同的 NSDates 返回不平等的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25905885/

相关文章:

html - Google Analytics for HTML inside ios native app

ios - 如何从 iOS9 中的 AddressDictionary 获取格式化地址 NSString?

ios - 测试NSDate比较的最佳方法是什么?

iphone - 将 NSString 转换为 nsdate 不起作用

ios - 设备 ID 未存储在服务器 IOS7 中

ios - Swift Json 响应解码

ios 获得今天凌晨 12 点

ios - 从 UTC 字符串获取日期

ios - 如何获得时间(下午 1 - 2 点)或(下午 2 - 3 点)

ios - 以编程方式创建 UIButton 比使用 Storyboard 模糊