NSDate() gives me good Universal Time (NOT local time) which is perfect for my purpose. I need to extract date components (Hour, Minute etc) from this NSDate but below code converts the time to local time. How can I extract the given universal date's components without altering them to local time zone:
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)
答案 0 :(得分:3)
您必须在日历上设置时区。
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