why the result of my date object always several hours behind the actual string that I want to convert? [duplicate]

こ雲淡風輕ζ 提交于 2021-01-29 07:08:58

问题


I am a junior iOS developer. and now I have problem when converting string to date object.

I don't know why the result (date object) always 7 hour behind the actual string I input. currently I am in Indonesia (GMT + 7), I don't know, but maybe it is related to the place where I live. here is the code I use

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.timeZone = Calendar.current.timeZone
    let x = dateFormatter.date(from: "2018-07-18 12:00:00")
    print(x)


result: 2018-07-18 05:00:00 +0000

how to fix this? really need your help


回答1:


Your code is working very well. There is nothing wrong with it. The value printed is 100% correct.

Date objects do not store anything about time zones and when printed, it will always be in the GMT (UTC+0) time zone. This is why +0000 appears at the end of the printed string. Date objects represent a point in time. 12:00 in Indonesia is the same point in time as 05:00 in GMT.

So whenever you want to see the Date object as a string in your time zone, you need to use a DateTimeFormatter like you did here and set the timeZone of the formatter.



来源:https://stackoverflow.com/questions/51397856/why-the-result-of-my-date-object-always-several-hours-behind-the-actual-string-t

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