首页 > 其他 > 详细

NSDateFormatter 基本用法

时间:2014-02-13 01:59:37      阅读:426      评论:0      收藏:0      [点我收藏+]

前言:iOS开发中NSDateFormatter是一个很常用的类,用于格式化NSDate对象,支持本地化的信息。与时间相关的功能还可能会用到NSDateComponents类和NSCalendar类等。本文主要列出NSDateFormatter常见用法。


 NSDate对象包含两个部分,日期(Date)和时间(Time)。格式化的时间字符串主要也是针对日期和时间的。[以下代码中开启了ARC,所以没有release。]

1、基础用法

bubuko.com,布布扣
bubuko.com,布布扣
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);
bubuko.com,布布扣
bubuko.com,布布扣

打印输出:10/29/12, 2:27 PM
这使用的系统提供的格式化字符串,通过 fmt.dateStyle 和 fmt.timeStyle 进行的设置。实例中使用的参数是 kCFDateFormatterShortStyle,此外还有:

bubuko.com,布布扣
bubuko.com,布布扣
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
};
bubuko.com,布布扣
bubuko.com,布布扣

2. 自定义区域语言
如上实例中,我们使用的是区域语言是 en_US,指的是美国英语。如果我们换成简体中文,则代码是:

1 fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];

 则对应的输出为:

bubuko.com,布布扣
bubuko.com,布布扣
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秒
};
bubuko.com,布布扣
bubuko.com,布布扣

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 星期一

NSDateFormatter 基本用法

原文:http://www.cnblogs.com/wangxiaofeinin/p/3546218.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!