views:

445

answers:

1

I have the following code in a production application which calculates a GMT date from the date the user enters:

NSDate *localDate = pickedDate;
    NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
    NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
    NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

The code was working fine, until the dreaded daylight savings time came into force in the UK last week.

How can I convert the date into GMT whilst taking into account daylight savings?

+1  A: 

NSDate uses an offset from an absolute value to represent time intervals. The basis is in GMT and all time intervals are in GMT, which is why you see the difference. If you want a string representation of your date (like for storing in a database or whatever), use the NSDateFormatter to create it in whichever specific time zone you need.

So, this will always give you a string representation (like for storing in mysql) of the date in GMT (with daylights savings times accounted for):

NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // e.g., set for mysql date strings
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSString* mysqlGMTString = [formatter stringFromDate:[NSDate date]];

This will give you the proper date string in GMT time regardless of the local time zone. Also, keep in mind that all relative measurements that you do with NSDate and time intervals have their basis in GMT. Use date formatters and calendar objects to convert them to more meaningful things when you present them to the user or if you need to do calendar calculations (e.g., displaying a warning that your subscription expires tomorrow).

EDIT: I forgot to add the time zone! Without it the formatter will use the system time zone.

Jason Coco
You can convert to NSDate using NSDateFormatter as well:http://stackoverflow.com/questions/1578577/nsdateformatter-datefromstring-will-not-parse-a-particular-date-string/1586083#1586083
Epsilon Prime
@Epsilon Prime: well yes, but he was specifically asking about working with dates and time zones not necessarily strings. I chose this example because it's a common reason people want to convert from a local time zone to another basis (like GMT).
Jason Coco