如何在swift中获取午夜的UTC日期
有人能帮我获取当前UTC日期时间吗。如何在swift中获取午夜的UTC日期,swift,nsdate,utc,swift2.3,Swift,Nsdate,Utc,Swift2.3,有人能帮我获取当前UTC日期时间吗。 我正在努力: let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let components = cal.components([.Day , .Month, .Year ], fromDate: NSDate()) let refDate = cal.dateFromComponents(components) 但是我得到了20
我正在努力:
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let components = cal.components([.Day , .Month, .Year ], fromDate: NSDate())
let refDate = cal.dateFromComponents(components)
但是我得到了2017年12月1日23:00:00
这是UTC当地时间。我想在午夜获取当前日期的UTC。
在数据库中,我将日期保存为秒数,但在服务器上,日期保存为2017年1月13日00:00:00,在swift中,我将获得2017年1月12日23:00:00,因此我无法获得值,因为它们不同,我不明白要获得相同的UTC需要做些什么。
在数据库中,我将日期保存为swift中的长秒数,我通过UInt64(floor(refDate!.timeintervalncesince1970))获取它。但日期不正确。您需要将
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)