谁能帮我获取当前的 UTC 日期时间。
我正在尝试:
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let components = cal.components([.Day , .Month, .Year ], fromDate: NSDate())
let refDate = cal.dateFromComponents(components)
但我得到 1/12/2017 23:00:00
这似乎是 UTC 本地时间。
我想在午夜获取当前日期的 UTC。
在数据库中,我将日期保存为秒数,但在服务器上它保存为 1/13/2017 00:00:00 并且很快我得到 1/12/2017 23:00:00 所以我无法获得值它们是不同的我不明白我需要做什么才能获得相同的 UTC。
在数据库中,我在 swift 中将日期保存为很长的秒数,我通过 UInt64(floor(refDate!.timeIntervalSince1970))
获取它,但日期不正确。
最佳答案
您需要将NSDateComponents
的hour
、minute
和second
属性设置为0
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.timeZone = NSTimeZone(name: "UTC")!
let components = cal.components([.Day , .Month, .Year,.Hour, .Minute, .Second], fromDate: NSDate())
components.hour = 0
components.minute = 0
components.second = 0
let refDate = cal.dateFromComponents(components)
或者从 iOS 8 你也可以使用 startOfDayForDate
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.timeZone = NSTimeZone(name: "UTC")!
let refDate = cal.startOfDayForDate(NSDate())
print(refDate)
关于swift - 如何在 swift 中获取日期的 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41634399/