Swift : Checking if 2 NSDates are the same

大兔子大兔子 提交于 2019-12-10 11:07:47

问题


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-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-31 13:56:50 +0000

Solution As 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

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()))

   }

回答1:


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

or

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

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




回答2:


You should be able to compare NSDates with == operator (xCode 6.2). I tried the following simple compare

let startDate = NSDate()
var dateComponents = NSDateComponents()           
var calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var endDate = calendar!.dateByAddingComponents(dateComponents, toDate: startDate, options: nil)

if(startDate == endDate) // true here
{
    println("equal")
}

if I change endDate

dateComponents.second = 5
endDate = calendar!.dateByAddingComponents(dateComponents, toDate: startDate, options: nil)

if(startDate == endDate) // false here
{
    println("equal")
}



回答3:


You can use this extension:

extension NSDate
{
    func isGreaterThanDate(dateToCompare : NSDate) -> Bool
    {
        if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending
        {
            return true
        }

        return false
    }


    func isLessThanDate(dateToCompare : NSDate) -> Bool
    {
        if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending
        {
            return true
        }

        return false
    }


    func isEqualToDate(dateToCompare : NSDate) -> Bool
    {    
        if self.compare(dateToCompare) == NSComparisonResult.OrderedSame
        {
            return true
        }

        return false
    }
}

the extension works fine check like:

var date1 : NSDate = NSDate()
var date2 : NSDate = date1.dateByAddingTimeInterval(-100)

print("\(date1)-----\(date2)\n")


if date1.isEqualToDate(date2) {
   print("date1 and date 2 are the same")

}else if date1.isLessThanDate(date2) {
   print("date 1 is less than date2")

 }else if date1.isGreaterThanDate(date2){
   print("date1 is more than date 2")
  }

and just change the value you add or subtract. Maybe you have to use a dateformatter for your dates




回答4:


I actually found this new method to fix the issue

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

     }


来源:https://stackoverflow.com/questions/29392717/swift-checking-if-2-nsdates-are-the-same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!