前言: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) { // date and time format styles
kCFDateFormatterNoStyle = 0, // 無輸出
kCFDateFormatterShortStyle = 1, // 10/29/12, 2:27 PM
kCFDateFormatterMediumStyle = 2, // Oct 29, 2012, 2:36:59 PM
kCFDateFormatterLongStyle = 3, // October 29, 2012, 2:38:46 PM GMT+08:00
kCFDateFormatterFullStyle = 4 // Monday, October 29, 2012, 2:39:56 PM China Standard Time
};
2. 自定義區域語言
如上實例中,我們使用的是區域語言是 en_US,指的是美國英語。如果我們換成簡體中文,則代碼是:
1 fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
則對應的輸出為:
typedef CF_ENUM(CFIndex, CFDateFormatterStyle) { // date and time format styles
kCFDateFormatterNoStyle = 0, // 無輸出
kCFDateFormatterShortStyle = 1, // 12-10-29 下午2:52
kCFDateFormatterMediumStyle = 2, // 2012-10-29 下午2:51:43
kCFDateFormatterLongStyle = 3, // 2012年10月29日 GMT+0800下午2時51分08秒
kCFDateFormatterFullStyle = 4 // 2012年10月29日星期一 中國標准時間下午2時46分49秒
};
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 星期一

