NSdate時間轉換問題

2021-06-19 15:22:42 字數 1752 閱讀 2329

使用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];  

NSDate 處理時間問題

nsdate類用於儲存時間值,同時提供了一些方法來處理一些基於秒級別時差 timeinterval 運算和日期之間的早晚比較等。a 建立或初始化可用以下方法 用於建立nsdate例項的類方法有 id date 返回當前時間 id datewithtimeintervalsincenow nstime...

NSDate時間操作

pragma mark nsdate 1.獲取時間date datewithtimeinterval nsdate date nsdate date 格林威治時間 本初子午線的放 nslog date nsdate date1 nsdate datewithtimeintervalsincenow ...

NSDate時間格式

1.formatte1r setdateformat yyyy mm dd hh mm ss a 如果時間格式是12小時制的,會返回格式 2011 11 11 08 30 30 下午 如果是24小時制的,格式是 2011 11 11 08 30 30 2.formatte1r setdateform...