从没有“时区校正"的组件创建 NSDate [英] Creating NSDate from components without "timezone correction"
问题描述
我有一个功能
func createDate(day: Int, month: Int, year: Int) -> NSDate {
var comp = NSDateComponents()
comp.day = day
comp.month = month
comp.year = year
var cal = NSCalendar.currentCalendar()
if var date = cal.dateFromComponents(comp) {
return date
}
return NSDate()
}
如果我用
createDate(07, 01, 1984)
输出为 1984-01-06 23:00:00 +0000
.我认为时区有一些影响.如何调整我的代码,使输出为 1984-01-07 00:00:00 +0000
?我在这里出了什么问题?我怎么糊涂了?
the output is 1984-01-06 23:00:00 +0000
. I assume that there is some influence from the time zone. How can I adjust my code so that the output will be 1984-01-07 00:00:00 +0000
? What am I getting wrong here? How am I confused?
推荐答案
不需要使用 NSDateComponents 来输入时间.NSCalendar 已经有一种方法可以让您使用本地时间输入日期.它被称为 dateWithEra.+0000"它不是您的本地时间 (CET),它是 UTC 时间.您的 timeZone 不与您的 NSDate 对象一起存储,仅存储您 localTime 输入的相应 UTC 日期和时间.
There is no need to use NSDateComponents to input time. NSCalendar already has a method for you to input your date using your local time. It is called dateWithEra. "+0000" it is not your localTime (CET) it is UTC time. Your timeZone is not stored with your NSDate object, only the corresponding UTC date and time for your localTime input.
let myDate = NSCalendar.currentCalendar().dateWithEra(1, year: 1984, month: 1, day: 7, hour: 0, minute: 0, second: 0, nanosecond: 0)!
myDate.descriptionWithLocale(NSLocale.currentLocale())! // "Saturday, January 7, 1984 at 12:00:00 AM Brasilia Standard Time"
NSTimeZone.localTimeZone().secondsFromGMT
这篇关于从没有“时区校正"的组件创建 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!