服務器給出UTC格式的日期和時間。utc和本地日期時間轉換
2012-11-28T10:32:15+01:00
的UTC將被格式化爲:2012-11-28 10:32:15
目前當地實際日期&時間爲2012-11-28 11:32:15
我要保存UTC格式的數據庫,並在後面的UI顯示前將其轉換爲用戶的當地日期和時間。我寫了下面的代碼。但時間偏移是錯誤的。儘管時間偏移量爲+ 1小時,它會在2小時內增加2小時而不是1小時。
NSDateFormatter *utc = [[NSDateFormatter alloc] init];
[utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[utc setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dtUTC = [utc dateFromString:@"2012-11-28 10:32:15"];
double i =[[NSTimeZone systemTimeZone] secondsFromGMTForDate:[NSDate date ]];
NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yy-MM-dd HH:mm:ss"];
[dfLocal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:i]];
NSDate *localDateTime= [dtUTC dateByAddingTimeInterval:i];
NSString *time =[dfLocal stringFromDate:localDateTime];
NSLog(@"original UTC %@ now local: %@", dtUTC, time);
和日誌:
time offset : 1.000000
original UTC 2012-11-28 10:32:15 +0000 now local: 12-11-28 12:32:15
應該2012-11-28 11:32:15
但給人2012-11-28 12:32:15
我到底做錯了什麼?
可以從中得到我的回答有些想法http://stackoverflow.com/questions/13583253/convert-nsstring -date-to-utc-date/13583368#13583368 –