如何在 swift 午夜获取日期的 UTC

How to get UTC for date in midnigs in swift

谁能帮我获取当前的 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,在 swift 中,我得到的是 1/12/2017 23:00:00,所以我可以'无法获取值,因为它们不同我不明白我需要做什么才能获得相同的 UTC。

在数据库中,我将日期保存为 swift 中的秒数 我在 UInt64(floor(refDate!.timeIntervalSince1970)) 之前得到它,但日期不正确。

您需要将 NSDateComponentshourminutesecond 属性 设置为 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)

或者从iOS8你也可以用startOfDayForDate

let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
cal.timeZone = NSTimeZone(name: "UTC")!
let refDate = cal.startOfDayForDate(NSDate())
print(refDate)