NSDateFormatter常見的使用方式

2022-04-02 09:02:27 字數 1594 閱讀 3493

nsdateformatter是nsformatter的子類,是用來表示輸出的時間格式。

下面貼出兩個時間的例子。

例子一、

- (void

)datestring1

列印結果如下:

2017-02-27

23:21:53.616 mytestworkproduct[4185:114496] datestring1:----2017-02-27 pm 15:21:53 monday

例子二、

- (void

)datestring2

列印結果如下:

2017-02-27

23:21:53.623 mytestworkproduct[4185:114496] datestring2:----2023年2月27日 星期一 gmt 下午3:21:53

例子分析:

從上面兩個方法與列印結果中可見,nsdateformatter型別設定通常設定三項:1.日前+時間設定;2.本地設定;3.時區設定。

1.前+時間設定

日前+時間設定分為兩類,一種是系統型別的設定,另一種是自定義設定

系統型別的設定是系統提供的列舉

英文

[[nslocale alloc] initwithlocaleidentifier:

@"en_us"];

typedef cf_enum(cfindex, cfdateformatterstyle) ;

中文fmt.locale = [[nslocale alloc] initwithlocaleidentifier:@"

zh_cn"];

typedef cf_enum(cfindex, cfdateformatterstyle) ;

自定義設定

1.[format setdateformat:@"

yyyy-mm-dd a hh:mm:ss eeee"];

2.[format setdateformat:@"

yyyy-mm-dd hh:mm:ss

"];

2.本地設定

本地設定中常用的是中文和英文

//

中文format.locale = [[nslocale alloc] initwithlocaleidentifier:@"

zh_cn"];

//英文

format.locale = [[nslocale alloc] initwithlocaleidentifier:@"

en_us

"];

3.時區設定。

有時候獲取的時間差了8小時,這是因為時區問題導致的,解決方法如下:

[format settimezone:[nstimezone timezonewithabbreviation:@"

utc"

]]; 或者

[format settimezone:[nstimezone timezoneforsecondsfromgmt:

0]];

這三種屬性任意設定,就可以獲得不同型別的時間格式

NSDateFormatter時區問題

使用nsdateformatter轉換時間字串時,預設的時區是系統時區,如我們使用一般都是北京時間 8 如果直接使用 cpp view plain copy print?dateformatter datefromstring 2012 01 01 00 00 00 你會發現實際轉換為2011 12...

IOS開發 NSDateFormatter的問題

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

NSDateFormatter相關整理

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