【问题标题】:Extract date components from a NSDate ignoring local time and time zones从 NSDate 中提取日期组件,忽略本地时间和时区
【发布时间】:2017-03-03 00:00:01
【问题描述】:

NSDate() 给了我很好的世界时间(不是本地时间),这对我的目的来说是完美的。我需要从此 NSDate 中提取日期组件(小时、分钟等),但下面的代码将时间转换为本地时间。如何在不将它们更改为本地时区的情况下提取给定的通用日期组件:

let date = NSDate()
print(date) // Prints 2016-10-20 20:10:20 +0000 (Good Universal Time) 
let calendar = Calendar.current
let hour = calendar.component(.hour, from date as Date)
print(hour) // Prints 16 (Bad local hour)

【问题讨论】:

    标签: swift nsdate


    【解决方案1】:

    您必须在日历上设置时区。

    let date = NSDate()
    print(date) // Prints 2016-10-20 20:10:20 +0000 (Good Universal Time)
    var calendar = Calendar.current
    calendar.timeZone = TimeZone(abbreviation: "UTC")!
    let hour = calendar.component(.hour, from: date as Date)
    print(hour) // Prints 20
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多