MattBlack MattBlack - 4 months ago 6x
Swift Question

Time stamp before or after

I have a timestamp in a database. I need to determine whether the stamp is before or after today's date at 7 AM.

How do I do that?


You need to be careful when comparing dates as timezone can cause a big headache. NSDate always stores time in UTC timezone. Depending on daylight saving times, GMT can be UTC+0 or UTC+1.

Give this a try:

// This extension is optional. It makes comparing dates easier
extension NSDate: Comparable {}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970

// This part simulates the time you get from the database
let dbCalendar = NSCalendar.currentCalendar()
dbCalendar.timeZone = NSTimeZone(name: "GMT")!
let timestampFromDB = dbCalendar.dateWithEra(1, year: 2016, month: 5, day: 30, hour: 10, minute: 0, second: 0, nanosecond: 0)!

// Convert 7AM today from user's time to UTC
let userCalendar = NSCalendar.currentCalendar()
let todayAt7 = userCalendar.dateBySettingHour(7, minute:0, second:0, ofDate: NSDate(), options: [])!

print(timestampFromDB < todayAt7)