NSDate comparison

I would like to compare two NSDates, however each date shows as "earlier" than todaysDate. Any ideas?

let compareResult = self.todaysDate.compare(self.date)

if compareResult == NSComparisonResult.OrderedDescending {
println("Today is later than date2")
} else {
println("Future")
}

      

To get "todaysDate"

let todaysDate = NSDate()
let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: todaysDate)
let hour = components.hour
let minutes = components.minute
let month = components.month
let year = components.year
let day = components.day
println(todaysDate)

      

This seal:

2014-11-12 14:48:48 +0000

      

and print for "date":

2014-10-24 07:24:41 +0000

      

It's on the Parse.com server.

thank

+3


source to share


3 answers


I think you might be interpreting the results compare

backwards. Check this. Each of the asserts

passes:



let today = NSDate()
let tomorrow = today.dateByAddingTimeInterval(24 * 60 * 60)
let yesterday = today.dateByAddingTimeInterval(-24 * 60 * 60)

assert(today.compare(tomorrow)  == .OrderedAscending)     // today < tomorrow
assert(today.compare(yesterday) == .OrderedDescending)    // today > yesterday
assert(today.compare(today)     == .OrderedSame)          // today == today

      

+10


source


If you want to support ==

, <

, >

, <=

or >=

to NSDate

s, you just need to declare it somewhere:

public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs === rhs || lhs.compare(rhs) == .OrderedSame
}

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedAscending
}

extension NSDate: Comparable { }

      

Implementation ==

and <

allows Comparable

you to deduce other comparison operators.



Using:

let date1 = NSDate()
let date2 = NSDate()

println(date2 > date1) // true
println(date2 < date1) // false
println(date2 == date2) // true

      

+10


source


try it! you can check another date by assigning it to strdate

    todaysDate = NSDate()
    println(todaysDate)

    var dateformmatter:NSDateFormatter = NSDateFormatter()
    dateformmatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
    let strdate:NSString = "2014-12-12 07:24:41";
    date = dateformmatter.dateFromString(strdate)!;
    println(date)

    let compareResult = todaysDate.compare(date)

    if compareResult == NSComparisonResult.OrderedDescending {
        println("Today is later than date2")
    } else {
        println("Future")
    }

      

+1


source







All Articles