Mick Walker
Mick Walker

Reputation: 3847

NSDate - GMT on iPhone

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?

Upvotes: 3

Views: 3250

Answers (1)

Jason Coco
Jason Coco

Reputation: 78393

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.

Upvotes: 6

Related Questions