SWIFT – Compare NSDATE

I want to compare two NSDates, but each date is displayed as “earlier” today. Any ideas?

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

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

Get “Today’s Date”

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 print is:

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

The printed matter of “Date” is:

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

This It is on the Parse.com server.

Thank you

I think maybe you Interpreting the backward results. Take a look at this. Each assertion passes:

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

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

I want to compare two NSDates, but each date is displayed as “earlier” today. Any ideas NS?

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

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

Get “Today’s Date”

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 print is:

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

The printed matter of “Date” is:

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

This It is on the Parse.com server.

Thank you

I think maybe you are explaining the more backward results. Take a look at this. Every One assertion passed:

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

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

Leave a Comment

Your email address will not be published.