2011-12-20 68 views
3

我想將我的本地日期([NSDate日期])轉換爲GMT以創建一個JSON字符串(/ Date(1324435876019-0000)/)。NSDate到GMTDate到JSON格式

當我將我的時鐘設置爲EST時區時,我的代碼正常工作,當我將時區更改爲PST時,我的代碼仍然用作EST。你能告訴我下面的代碼是什麼問題?

 NSDate *localDate = [NSDate date]; 
    NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method 
    NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset; 
    NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval]; 
    NSString *time = [NSString stringWithFormat:@"/Date(%@-0000)/", [NSNumber numberWithLongLong:[gmtDate timeIntervalSince1970] * 1000]]; 
+0

當前時間是2011-12-20 05:15:00 +0000但是,如果我NSLog gmtDate我出去把作爲1)ESt時區:2011-12-21 03:15: 00 +0000 2)PSTtime區域:2011-12-21 06:15:00 +0000。這是錯誤的。我想我沒有得到正確的格林威治時間日期。你怎麼看 ? – AAV 2011-12-20 22:18:27

回答

7

您可以通過簡單地調用timeIntervalSince1970得到劃時代GMT時間。

NSString *time = [NSString stringWithFormat:@"/Date(%lld-0000)/", 
        (long long)([[NSDate date] timeIntervalSince1970] * 1000)]; 
+0

第一件事timeIntervalSince1970將在第二個給你,我們需要傳遞毫秒的JSON。我首先實現了這個邏輯,但我無法找到正確的答案。 – AAV 2011-12-21 16:44:56

+0

已更新的答案。您無需進行任何時區計算即可獲取GMT時間,只需一個班輪即可。 – Joe 2011-12-21 16:55:58

+0

@AmitVyawahare:timeIntervalSince1970使用秒作爲其單位,但返回一個NSTimeInterval,它是一個雙精度值,具有相當的分數精度。所以喬的解決方案是正確的,應該給你毫秒的分辨率。 – Tommy 2011-12-21 17:28:08

0

@joe和@tommy你是對的。即使我按照你提到的方式實施。問題出在服務器數據庫中。我發現了一個黑客。我只需要添加18000(5小時)秒到當前的當地日期,我很好。所以代碼是

 NSDate *localDate = [NSDate date]; 
    NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] + 18000; 
    NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval]; 

    NSString *time = [NSString stringWithFormat:@"/Date(%@-0000)/", [NSNumber numberWithLongLong:[gmtDate timeIntervalSince1970] * 1000]]; 
+0

這不是一個很好的解決方案(正如你知道自從你使用hack這個詞),不要忘記有'EST'和'EDT'。您的服務器只需要將時間顯示回正確的時區,也許解決方法是將「-0000」更改爲「-0500」(EST)/「 - 0400」(EDT)。 – Joe 2011-12-21 21:57:48

+0

你是正確的黑客不好,但直到點服務器不固定,我必須使用相同的Crapy代碼。謝謝你,--AV – AAV 2011-12-21 22:32:00