2012-11-28 190 views
0

服務器給出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 我到底做錯了什麼?

+0

可以從中得到我的回答有些想法http://stackoverflow.com/questions/13583253/convert-nsstring -date-to-utc-date/13583368#13583368 –

回答

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"]; 

NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init]; 
[dfLocal setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
[dfLocal setTimeZone:[NSTimeZone localTimeZone]]; 

NSString *time =[dfLocal stringFromDate:dtUTC]; 
NSLog(@"original UTC %@ now local: %@", dtUTC, time); 

和日誌:

time offset : 1.000000 
original UTC 2012-11-28 10:32:15 +0000 now local: **2012-11-28 11:32:15** 

感謝球員的努力幫助

+0

偉大..它解決了我的問題..感謝:) –

0

改變這一行

[dfLocal setDateFormat:@"yy-MM-dd HH:mm:ss"]; 

[dfLocal setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 

快樂編碼替換它。!!!!!

+0

不起作用,因爲它與添加時間偏移無關。我之前嘗試過:-) –

0

也試試這個代碼..

NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone]; 
NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; 

NSDate *dtUTC = [utc dateFromString:@"2012-11-28 10:32:15"]; 

NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:sourceDate]; 
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:sourceDate]; 
NSTimeInterval gmtInterval = gmtOffset - currentGMTOffset; 

NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init]; 
[dfLocal setDateFormat:@"yy-MM-dd HH:mm:ss"]; 
NSDate* localDateTime = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:dtUTC] autorelease]; 
NSString *time =[dfLocal stringFromDate:localDateTime]; 
NSLog(@"original UTC %@ now local: %@", dtUTC, time); 

我希望這會幫助你...

+1

我也會看看那個版本。謝謝 –

相關問題