Swift : Checking if 2 NSDates are the same

半腔热情 提交于 2019-12-06 05:05:13

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.

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")
}

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

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

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