Handling time zones in Cocoa

五迷三道 提交于 2019-12-11 14:49:36

问题


I just want to clarify if I am understanding how dates & time zones work.

Basically, I have a date string @"2008-07-06 12:08:49" that I want to convert to an NSDate. I want this date and time to be in whatever the current user's time zone is set in. So if they are in GMT or HST, it's still 12:08:49.

If I have date in unix form 1215382129 (UTC) and my time zone is set to London (GMT), the outputted date from NSLog() is:

2008-07-06 12:08:49 +0100

If I then change my time zone to Hawaii (HST) and output the same date, I get:

2008-07-06 12:08:49 -1000

This seems to work fine, but I was under the impression to get the time in Hawaiian, I'd have to physically add the time difference (-10hrs) to the unix time stamp. Is this not required then?

Does that mean, whatever date and time a unix time is pointing to, it always points to the same date and time in whatever time zone a user is in?

Hope this makes sense!

Edit

I've just realised (thanks to Kevin Conner!) that in fact NSDateFormatter is creating different unix timestamps for that date string depending on the current timezone! So I was totally wrong!! :-)


回答1:


Disclaimer, I'm mostly a Java guy. But Cocoa seems to work like the Java library in this regard: Dates are zoneless timestamps. Time zones are in the domain of formatting dates for display. In other words, the internal format doesn't consider time zones, it's all in UTC. Time zones are relatively a convenience for humans, so they are in the display/parsing side.

I noticed there is a setTimeZone: method on NSDateFormatter. Try calling that on your formatter before performing the format.



来源:https://stackoverflow.com/questions/1980903/handling-time-zones-in-cocoa

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