JimmyJammed
JimmyJammed

Reputation: 9698

iOS - Proper formatting of timestamps between mySQL (apache) and iOS (NSDate)

I am trying to pass a timestamp (yyyy-MM-dd HH:mm:ss) from mySQL (running on apache) to iOS. Currently, mysql is set to this timezone:

default-time-zone='+00:00'

When I pass this timestamp down to iOS, I use this code to convert the string to an NSDate:

-(NSDate *)formatDateWithString:(NSString *)dateString{
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
     NSDate* date = [dateFormatter dateFromString:dateString];
     NSLog(@"Formatted Timestamp: %@ - Original Timestamp: %@", date,dateString);
     return date;
}

This is the output for a mySQL timestamp of 2013-04-17 16:33:56:

Formatted Timestamp: 2013-04-17 23:33:56 +0000 - Original Timestamp: 2013-04-17 16:33:56

Why is iOS adding 7 hours? (FYI - I am located in San Francisco, Ca so I am sure it has something to do with my timezone being PDT. Just not sure why it is being converted that way when I don't specify it to be).

It is important to use the most "universal" timestamp possible in my app as I may have users all over the world and don't want to fuss with a lot of conversions. I want to be able to store the timestamps in mySQL, then just compare the differences between the stored server timestamp and the current server timestamp. I would prefer to not have to use a web request to get the "server time" everytime I need to do a comparison if possible.

UPDATE

By adding this line of code to my dateFormatter, it seems that the two times are now matching correctly:

[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

However, can anyone verify that it will always continue to match, regardless of the time of year? (i.e. Daylight Savings time, etc.)

Upvotes: 1

Views: 2658

Answers (1)

Anupdas
Anupdas

Reputation: 10201

By default NSDateFormatter is set to localTimeZone. Since your dateString didn't had timezone information, it calculated the time wrt to localTimeZone. If you know that the timezone of your dateString is UTC then you need to set that to dateFormatter.

NSDate represents absolute time, the representation can vary wrt timeZones but it is a unique value and it will not be affected by daylight savings.

-(NSDate *)formatDateWithString:(NSString *)dateString{
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
     [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
     NSDate* date = [dateFormatter dateFromString:dateString];
     NSLog(@"Formatted Timestamp: %@ - Original Timestamp: %@", date,dateString);
     return date;
}

Upvotes: 3

Related Questions