NSDateFormatter時區問題

2021-06-04 22:51:01 字數 1752 閱讀 7839

使用nsdateformatter轉換時間字串時,預設的時區是系統時區,如我們使用一般都是北京時間(+8),

如果直接使用

[cpp]view plain

copy

print?

[dateformatter datefromstring:@

"2012-01-01 00:00:00"

];  

你會發現實際轉換為2011-12-31 16:00:00,少了8小時

所以我們要先指定時區為gmt再轉換,如下:

[cpp]view plain

copy

print?

static

nsstring *global_timeformat = @

"yyyy-mm-dd hh:mm:ss"

;  static

nsstring *global_timebase = @

"2012-01-01 00:00:00"

;  nstimezone* localzone = [nstimezone localtimezone];  

nstimezone* gtmzone = [nstimezone timezoneforsecondsfromgmt:0];  

nsdateformatter *dateformatter = [[nsdateformatter alloc] init];  

[dateformatter setdateformat:global_timeformat];  

[dateformatter settimezone:gtmzone];  

nsdate *bdate = [dateformatter datefromstring:global_timebase];  

nsdate *day = [nsdate datewithtimeinterval:3600 sincedate:bdate];  

[dateformatter settimezone:localzone];  

nslog(@"currenttime = %@"

, [dateformatter stringfromdate:day]);  

還可以如下:

[cpp]view plain

copy

print?

nstimezone* localzone = [nstimezone localtimezone];  

nstimezone* gtmzone = [nstimezone timezoneforsecondsfromgmt:0];  

nsdateformatter *dateformatter = [[nsdateformatter alloc] init];  

[dateformatter setdateformat:global_timeformat];  

[dateformatter settimezone:gtmzone];  

nsdate *bdate = [dateformatter datefromstring:global_timebase];  

nsdate *day = [nsdate datewithtimeinterval:(3600 + [localzone secondsfromgmt]) sincedate:bdate];  

nsstring *text = [dateformatter stringfromdate:day];  

IOS開發 NSDateFormatter的問題

今天下午遇到乙個問題.描述 找userdate之前大約三個月 相當於90天 的日期是多少?方法 使用了下面的方法 nsdate threemonthbeforedate nsdate datewithtimeinterval 60 60 24 30 3 sincedate userdate 但是結果...

NSDateFormatter相關整理

formatter譯為格式,相應的nsdateformatter就相當於是nsdate的轉換類,將nsdate轉換為另一種格式,或轉換回來。nsdate沒有自己的輸出,需要借助nsdateformatter以相應格式輸出。這差不多就是nsdateformatter的作用了吧。常用的方法並不複雜,幾條...

NSDateFormatter 相關問題

今天碰到伺服器傳過來的日期格式不是常見的,轉換格式的時候遇到點問題.如日期 字串 為 nov 12 2015,dec 2 2015 轉為 11 12 2015 12 02 2015.核心 如下.nsdateformatter dateformatter nsdateformatter alloc i...