2011-05-29 78 views
0

我從我的MySQL數據庫中檢索到的NSString(日期)在格林尼治標準時間+000(倫敦),格式如下:12/05/2011 5: 21:29 PM。將NSDate從GMT + 0(倫敦)轉換爲用戶的TimeZone

我想知道如何將其轉換爲用戶的時區,以便如果用戶在中國,例如,它就是中國時區的那個日期。

回答

4

在您的輸入NSDateFormatter上使用setTimeZone:。 (在內部,NSDate s爲的時區無關。)

如:

// The default time zone for a formatter is the time zone of the user's locale 
NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init]; 
[localFormatter setDateStyle:NSDateFormatterShortStyle]; 
[localFormatter setTimeStyle:NSDateFormatterMediumStyle]; 

NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc] init]; 
[gmtFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"]; 
[gmtFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

NSDate *date = [gmtFormatter dateFromString:gmtDateString]; 
NSString *locallyFormattedDate = [localFormatter stringFromDate:date]; 

[localFormatter release]; 
[gmtFormatter release]; 

雖然...我不認爲這需要DST考慮,如果在指定時間DST設置爲比當前設置不同。

+0

'gmtDateString'未定義。 – memmons 2013-07-02 23:23:17

+0

gmtDateString應該是您的GMT日期字符串。 ;) – Wevah 2014-08-05 21:26:15

-2

使用initWithTimeInterval:sinceDate:可以創建一個加/減小時數的日期對象。這將在幾秒鐘內完成,因此提前3小時將是initWithTimeInterval:10800 sinceDate:(originalDate)。 MM:這將給予你叫那個對象上-description將顯示爲(從蘋果文檔)

在國際格式 YYYY-MM-DD HH的 接收器的字符串表示的格式SS ±HHMM,其中±HHMM 代表與GMT相差 小時和分鐘的時區偏移量(例如, 例如「2001-03-24 10:45:32 +0600」)。

所以它會包含時間間隔。

編輯: 對不起,我正在使用錯誤的init方法,那就是你正在尋找的方法,initWithTimeInterval:sinceDate :.您創建一個新的NSDate,用於增加或減少時區前後的秒數。

+0

我不明白我可以如何轉換時區之間的日期。 – 2011-05-29 00:58:36

+0

我編輯我的答案使用正確的方法,initWithTimeInterval:SinceDate。 – Chris 2011-05-29 01:05:02

+0

所以我需要知道每個時區的偏移量? – 2011-05-29 01:07:40