2015-02-08 77 views
0

我從一些RESTful服務時間戳這種格式:如何從iOS中的JSON解析Unix時間戳?

"/Date(1357306469510+0100)/" 

我發現一些職位提供代碼來解析這個創造它的等效NSDate對象,例如:

NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; 
NSInteger startPosition = [jsonDate rangeOfString:@"("].location + 1; 
NSTimeInterval unixTime = [[jsonDate substringWithRange:NSMakeRange(startPosition, 13)] doubleValue]/1000; 
NSDate *date = [[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset]; 

,但它不似乎處理服務器時間戳的時區(+0100)。

有人可以提供一個完整的解決方案,或告訴我在哪裏可以找到它?

在此先感謝

+0

你想顯示的時區或沒有? – 2015-02-08 17:49:43

+0

@FawadMasud我需要考慮時區在'NSDate'對象中有正確的時間 – AppsDev 2015-02-09 06:33:17

回答

0

以下代碼應該可以工作。請參閱我的在線評論以獲取解釋。從本質上講,你必須弄清楚格林尼治標準時間後多少秒,你的服務器時間被抵消了(在你的情況下,+3600秒)。

//The date string 
NSString *dStr = @"/Date(1357306469510+0100)/"; 

//Get the unix time 
NSUInteger unixStart = [dStr rangeOfString:@"("].location + 1; 
NSUInteger unixEnd = ([dStr rangeOfString:@"+"].location == NSNotFound ? [dStr rangeOfString:@"-"].location : [dStr rangeOfString:@"+"].location); 
double unixTime = [[dStr substringWithRange:NSMakeRange(unixStart, unixEnd - unixStart)] doubleValue]/1000; 
NSLog(@"%f", unixTime); 

//Get the timezone 
NSUInteger tzStart = unixEnd; 
NSUInteger tzEnd = [dStr rangeOfString:@")"].location; 
float tzOffset = [[dStr substringWithRange:NSMakeRange(tzStart, tzEnd - tzStart)] floatValue]/100 * 60 * 60; 
NSLog(@"%f", tzOffset); 

//Calculate the date 
NSDate *date = [[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:tzOffset]; 
NSLog(@"%@", date); 
+0

感謝您的迴應。如果我登錄從代碼中得到的'NSDate',會顯示'2015-02-09 07:52:25 + 0000',而記錄'[NSDate date]'打印'2015-02-09 06:52: 25 + 0000' ...我需要得到'2015-02-09 07:52:25 + 0100'或'2015-02-09 06:52:25 + 0000' – AppsDev 2015-02-09 06:57:55

+0

@AppsDev你確定你輸入的日期是正確的?我測試了它,它似乎爲我工作...我用這個網站,得到了unix時間戳,並將其放入字符串:http://www.epochconverter.com/ – rebello95 2015-02-09 07:06:04

+0

它看起來像行爲是正確的.. 。如果我添加時區的偏移量,我可以得到毫秒的總數,但我並不是在告訴NSDate這個毫秒值是+1時區,它認爲是+0時區...所以我應該用某種方式如果我提供時區與JSON的偏移量,或者讓'NSDate'的時區保持爲+0並且不提供時區與JSON的偏移量,那麼它的時區爲+1的'NSDate' – AppsDev 2015-02-09 07:32:16

0

據我所知,Unix時間戳沒有時區字段,它需要GMT作爲標準。如果您想將時區與時區轉換爲當地時間,請使用GMT與差分相加或減去秒數。當您從

NSTimeInterval unixTime = [[jsonDate substringWithRange:NSMakeRange(startPosition, 13)] doubleValue]/1000; 

附加得到的時間間隔3600秒的unixTime,

unixTime = unixTime+3600.0;//covering the offset. One hour in your case. 

顯示此時間

NSDate *date = [NSDate dateWithTimeIntervalSince1970:unixTime];