2014-07-23 50 views
-2

我想將一個Unix時間字符串轉換爲Xcode中的日期,但我一直得到錯誤的時間兩個小時。我無法弄清楚我做錯了什麼。有人能幫助我嗎?從Unix轉換時間給出了錯誤的結果

NSString *unixTime = @"1402473600"; 
NSTimeInterval timeStamp = [unixTime doubleValue]; 
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp]; 

它給了我:2014年6月11日10:00:00 CEST

...但它應該是:2014年6月11日08:00:00 CEST

+0

這是「Wed,2014年6月11日08:00:00 GMT」,根據http://www.onlineconversion.com/unix_time.htm – trojanfoe

+0

...所以這是正確的。 – trojanfoe

+0

是的,但這不是xcode給我的...... – turingtested

回答

1

的Xcode返回UTC + 0時區中正確的值。不要忘記CEST是UTC + 2。這裏是測試它的代碼片段:

// your code 
NSString *unixTime = @"1402473600"; 
NSTimeInterval timeStamp = [unixTime doubleValue]; 
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp]; 
NSLog(@"%@", date); // 08:00:00 +0000 

// CEST, UTC+2 formatting 
NSDateFormatter *localDF = [[NSDateFormatter alloc] init]; 
[localDF setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CEST"]]; // which is CEST, which is UTC+2 
[localDF setDateFormat:@"HH:mm:ss Z"]; 

NSLog(@"%@", [localDF stringFromDate:date]); // 10:00:00 +0200 

您可以將您的日期轉換爲CEST時區。根據結果​​,你可以根據需要的時區給定日期轉換爲新日期變量與調整值或創建的字符串表示:

變定日期的1.返回字符串表示與時區:

NSDateFormatter *cestDF = [[NSDateFormatter alloc] init]; 
[cestDF setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CEST"]]; // which is CEST, which is UTC+2 
[cestDF setDateFormat:@"HH:mm:ss Z"]; 
NSString *cestDateStr = [cestDF stringFromDate:date]; 

變2.新建和調整日期對象:

NSTimeInterval timeZoneOffset = [[NSTimeZone timeZoneWithAbbreviation:@"CEST"] secondsFromGMT]; 
NSTimeInterval cestTimeInterval = [date timeIntervalSinceReferenceDate] + timeZoneOffset; 
NSDate *cestDate = [NSDate dateWithTimeIntervalSinceReferenceDate:cestTimeInterval]; 

注:NSDate沒有時區的概念裏面我t,所以你應該記住哪個時區是你的NSDate變量。

+0

您的轉換使其錯誤2小時。我將「+ timeZoneOffset」更改爲「 - timeZoneOffset」。 然後它變得正確。 – turingtested

+0

如果你減去,你會得到6:00。你收到UTC + 0的unixTime嗎? – Keenle

+0

您應該使用NSDateFormatter或使用NSTimeZone手動調整給定日期來轉換日期。如果您因此而變更了兩個變體,則會調整兩次。 – Keenle