Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 251
Mick Walker Avatar asked Feb 19 '26 05:02

Mick Walker


1 Answers

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.

like image 148
Jason Coco Avatar answered Feb 21 '26 22:02

Jason Coco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!