【问题标题】:Comparison of two identical NSDates returning unequal outcome比较两个相同的 NSDates 返回不相等的结果
【发布时间】:2014-09-18 06:40:27
【问题描述】:

我正在比较两个名为 serverDatelocalDate 的 NSDate。尽管两个日期的输出时间相同,但我仍然认为serverDatelocalDate 更新。

这是我的比较代码:

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",它输出以下内容:Server date: 2014-09-17 23:20:02:5090000000-0700, local date: 2014-09-17 23:20:02:5090000000-0700。但即便如此,serverDate 仍被视为较近的日期。

我做错了什么?感谢您的意见。

【问题讨论】:

  • NSLog(@"%f, %f", [serverDate timeIntervalSinceReferenceDate], [localDate timeIntervalSinceReferenceDate]) 注销后会得到什么。
  • 好电话@KudoCC!当我注销它时,我分别得到两个日期的432714002.509000, 432714002.508961。我想如果有一种方法可以将最接近的 1/10 秒舍入,那将是最好的解决方案。
  • 你也不需要else if,因为else会产生同样的效果。
  • 关于else if 确实如此。将更改代码。

标签: ios nsdate


【解决方案1】:

你不应该使用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");
}

希望对你有帮助

【讨论】:

  • 如果this 可以作为参考,NSDate 无论如何都会使用NSTimeInterval 进行比较。
  • 同意,但为什么不使用 iOS 提供的东西作为属性。
  • 我不反对;我的评论仅供参考。
【解决方案2】:

这将帮助你它对我有用

if ([serverDate isEqualToDate: localDate])
    {
        NSLog(@"Date are same");
    }else
{
 NSLog(@"Date are not equal")
}

【讨论】:

  • 感谢您添加答案。虽然isEqualToDate 很棒,但我真正想知道的是一个日期是否晚于另一个日期。我想在这里使用&gt;&lt; 不理想?
  • 如果 ([serverDate compare:localDate] == -1) { NSLog(@"serverDate is later than localDate"); 这将对您有所帮助} else if ([serverDate compare:localDate] == 1) { NSLog(@"serverDate 早于 localDate"); } else { NSLog(@"日期相同"); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多