时间戳之前或之后

时间:2016-05-30 20:57:56

标签: swift date cocoa cocoa-touch

我在数据库中有一个时间戳。我需要确定邮票是在今天上午7点之前还是之后。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

比较日期时需要小心,因为时区会引起很大的麻烦。 NSDate始终以UTC时区存储时间。根据夏令时,英国当地时间可以是UTC + 0或UTC + 1.

尝试一下:

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