Creating NSDate from components without “timezone correction”

假装没事ソ 提交于 2019-12-23 07:00:30

问题


I have a function

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()
}

If I call it with

createDate(07, 01, 1984)

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?


回答1:


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



回答2:


Don't worry about the log output. It will be an unformatted date. The actual date seems to be exactly what you intended.

If you want to show the exact date, you have to display it using a NSDateFormatter.



来源:https://stackoverflow.com/questions/28792312/creating-nsdate-from-components-without-timezone-correction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!