NSDateFormatter時間函式

2022-08-10 05:12:16 字數 2427 閱讀 9480

前言:ios開發中nsdateformatter是乙個很常用的類,用於格式化nsdate物件,支援本地化的資訊。與時間相關的功能還可能會用到nsdatecomponents類和nscalendar類等。本文主要列出nsdateformatter常見用法。

nsdate物件包含兩個部分,日期(date)和時間(time)。格式化的時間字串主要也是針對日期和時間的。[以下**中開啟了arc,所以沒有release。]

1、基礎用法

1 nsdate* now =[nsdate date];

2 nsdateformatter* fmt =[[nsdateformatter alloc] init];

3 fmt.datestyle =kcfdateformattershortstyle;

4 fmt.timestyle =kcfdateformattershortstyle;

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

en_us"];

6 nsstring* datestring =[fmt stringfromdate:now];

7 nslog(@"

%@", datestring);

列印輸出:10/29/12, 2:27 pm

這使用的系統提供的格式化字串,通過 fmt.datestyle 和 fmt.timestyle 進行的設定。例項中使用的引數是 kcfdateformattershortstyle,此外還有:

typedef cf_enum(cfindex, cfdateformatterstyle) ;
2. 自定義區域語言

如上例項中,我們使用的是區域語言是 en_us,指的是美國英語。如果我們換成簡體中文,則**是:

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

zh_cn

"];

則對應的輸出為:

typedef cf_enum(cfindex, cfdateformatterstyle) ;
世界通用的區域語言**,詳見 international components for unicode (icu),  

3. 自定義日期時間格式

nsdateformatter提供了自定義日期時間的方法,主要是通過設定屬性 dateformat,常見的設定如下:

1 nsdate* now =[nsdate date];

2 nsdateformatter* fmt =[[nsdateformatter alloc] init];

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

zh_cn"];

4 fmt.dateformat = @"yyyy-mm-dd't'hh:mm:ss";

5 nsstring* datestring =[fmt stringfromdate:now];

6 nslog(@"

%@", datestring);

列印輸出:2012-10-29t16:08:40

除了上面列出的,還可以指定很多格式,詳見。

結合設定locale,還可以列印出本地化的字串資訊。

1 nsdate* now =[nsdate date];

2 nsdateformatter* fmt =[[nsdateformatter alloc] init];

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

zh_cn"];

4 fmt.dateformat = @"

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

5 nsstring* datestring =[fmt stringfromdate:now];

6 nslog(@"

\n%@

", datestring);

列印輸出:2012-10-29 下午 16:25:27 星期一

4. 自定義月份星期等字元

nsdateformatter中同樣提供了相應的方式,去修改這些字元。一般情況下,使用相應區域語言下面的預設字元就ok了。但是你的確有這個需求,那麼也是可以辦到的。相應的方法非常多,如下:

managing am and pm symbols

managing weekday symbols

managing month symbols

managing quarter symbols

managing era symbols

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的作用了吧。常用的方法並不複雜,幾條...