Question

I have a date, 2010-08-23 13:30:00 -0400 and I'm trying to get it in the UTC +2 time zone. The difference in seconds is 21600 but when I call [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];, I get 2010-08-24 01:30:00 +0200 which should be 2010-08-23 19:30:00 +0200. Any idea what I'm doing wrong?

Was it helpful?

Solution

A date object represents a specific moment in time, irrespective of what different people's clocks might have said at that time.

Time zones become involved when you want to display the date, since you'll typically display what the user's clock would have said (or is saying, or will say) at that time. This is exactly what happens when you NSLog an NSDate: The date's description is that moment of time represented in your local time zone.

Adding to or subtracting from an NSDate is not time zone conversion. Addition and subtraction produce NSDates representing other moments in time; in your case, you're creating an NSDate for a moment 6 hours later from the moment you started with, not the same moment on the other side of the planet.

To simplify, time zone conversion is looking at the same time in different points in space (different sections of the planet's surface), whereas date addition and subtraction are computing different times.

There is no time zone conversion for an NSDate, because it isn't in a time zone to begin with. A time zone only becomes involved when you format the date for that time zone. So, to display that date in some other time zone, just do that. Typically, this means supplying the desired time zone to your date formatter.

OTHER TIPS

I see that the date you get back has a different timezone +200 not -400. If you notice you will see that that result is exactly 12 hours (or 6 hours + 6 hours) later than your original date. Did you by chance change the locale as well when you made the new date? When you made the change that started giving you +200 instead of -400 the system automatically adjusted the time to compensate, then you added another 6 hours to the date. NSDate stores all dates as a time interval since 1 Jan 2001 GMT and adjusts for timezones as needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top