【问题标题】:Time stamp before or after [closed][关闭]之前或之后的时间戳
【发布时间】:2016-05-30 20:57:56
【问题描述】:

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

我该怎么做?

【问题讨论】:

  • 你的数据库是什么?它是否与时区一起存储?如果不是,我应该假设它在哪个时区?
  • 嗨,现在是格林威治标准时间
  • 是用户所在时区的早上 7 点还是 GMT?
  • 如果是正好早上 7 点呢?应该在之前还是之后考虑还是第三种情况?
  • 嗨,在用户时区,是的,正好是早上 7 点

标签: swift date cocoa cocoa-touch


【解决方案1】:

比较日期时需要小心,因为时区可能会引起很大的麻烦。 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)

【讨论】:

  • 看准了!非常感谢!
  • GMT 永远不会改变,它永远不会是 UTC+1。您可能的意思是英国时间会发生变化,一年中的部分时间是格林威治标准时间,而在夏季是英国夏令时(UTC+1)。正如你所说,你需要小心时区;-)
  • @CRD 尝尝我自己的药。该死的夏令时!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-21
相关资源
最近更新 更多