【问题标题】:How to get UTC for date in midnigs in swift如何在 swift 中获取 UTC 日期
【发布时间】:2017-05-28 19:30:43
【问题描述】:

谁能帮我获取当前的 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)) 得到它,但日期不正确。

【问题讨论】:

    标签: swift nsdate utc swift2.3


    【解决方案1】:

    您需要将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)
    

    或者从 iOS 8 你也可以使用startOfDayForDate

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

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 2021-04-13
      • 2011-10-17
      • 2015-01-08
      • 1970-01-01
      • 2018-01-17
      • 2018-09-13
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多