views:

360

answers:

1

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!! :-)

+3  A: 

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.

Kevin Conner
Ahh, interesting! I didn't realise `NSDateFormatter` used time zones. It would appear that it's automatically setting it from the system default. And it's creating a different unix timestamps depending on the zone! Thanks for this!
Michael Waterfall
I haven't confirmed this, but I think you'll find the same to be true of date parsing: When you parse a date string, it will assume the string is in your system time zone, unless you configure the parser differently. Cheers :)
Kevin Conner