1

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.)

4

1 回答 1

3

默认情况下,NSDateFormatter 设置为 localTimeZone。由于您的 dateString 没有时区信息,因此它计算了 localTimeZone 的时间。如果您知道 dateString 的时区是 UTC,那么您需要将其设置为 dateFormatter。

NSDate 表示绝对时间,表示可以随 timeZones 变化,但它是一个唯一值,不受夏令时的影响。

-(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;
}
于 2013-04-17T16:53:56.950 回答