本文介绍了Swift:检查 2 个 NSDates 是否相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的很简单,我确定这是 swift 中的一个错误.我正在尝试检查 2 个 NSDates 是否相同.即使认为打印输出低于

Really simple one, I am sure this is a bug in swift. I am trying to check if 2 NSDates are the same. This statement never passes even thought the printout is below

println("\(statistics.startDate) \(healthObject.date)")

if healthObject.date.isEqualToDate(statistics.startDate)
{
      healthObject.flights =  Int(quantity.doubleValueForUnit(HKUnit.countUnit()))
      println(Int(quantity.doubleValueForUnit(HKUnit.countUnit())))
}

2015-03-30 13:56:50 +0000 2015-03-30 13:56:50 +0000

2015-03-30 13:56:50 +0000 2015-03-30 13:56:50 +0000

2015-03-30 13:56:50 +0000 2015-03-31 13:56:50 +0000

2015-03-30 13:56:50 +0000 2015-03-31 13:56:50 +0000

2015-03-31 13:56:50 +0000 2015-03-30 13:56:50 +0000

2015-03-31 13:56:50 +0000 2015-03-30 13:56:50 +0000

2015-03-31 13:56:50 +0000 2015-03-31 13:56:50 +0000

2015-03-31 13:56:50 +0000 2015-03-31 13:56:50 +0000

解决方案正如一位回复的很棒的人所指出的那样,直到次秒级之前,日期可能都相同.奇怪的是,这些值是否来自 HealthKit

SolutionAs pointed out by one the awesome people who replied, the dates are probably the same up until sub second level. The odd part is, is these values are coming from HealthKit

在 iOS8 中对我有用的是:

What works for me in iOS8 is:

   if let dif = calender?.compareDate(statistics.startDate, toDate: healthObject.date, toUnitGranularity: NSCalendarUnit.SecondCalendarUnit)
   {
      println(Int(quantity.doubleValueForUnit(HKUnit.countUnit())))
      println("\(statistics.startDate) \(healthObject.date)")
      healthObject.flights =  Int(quantity.doubleValueForUnit(HKUnit.countUnit()))

   }

推荐答案

检查日期是否相等的最简单方法是使用 NSDate.isEqualToDate() 方法.

The simplest way to check if dates are equal is to use NSDate.isEqualToDate() method.

NSCalendar.currentCalendar().compareDate(date1, toDate: date2, toUnitGranularity: NSCalendarUnit.CalendarUnitSecond)

如果您使用了相当多的日期算术检查这个库.

If you are using quite a bit of date arithmetic check this library.

这篇关于Swift:检查 2 个 NSDates 是否相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:58