NSDateFormatter代表一个日期格式器,它可以完成NSDate与NSString之间的转换。
使用NSDateFormatter完成NSDate与NSString之间转换的步骤如下:
1⃣️创建一个NSDateFormatter对象。
2⃣️调用NSDateFormatter的setDateStyle: ,setTimeStyle:方法设置格式化日期,时间的风格。其中,日期,时间风格支持如下几个枚举值。
-->NSDateFormatterNoStyle: 不显示日期,时间的风格。
-->NSDateFormatterShortStyle: 显示“短”的日期,时间风格。
-->NSDateFormatterMediumStyle: 显示“中等”的日期,时间风格。
-->NSDateFormatterLongStyle: 显示“长”的日期,时间风格。
-->NSDateFormatterFullStyle: 显示“完整”的日期,时间格式。
如果打算使用自己的格式模版,可以调用NSDateFormatter的setDateFormatter: 方法设置日期,时间的模版。
3⃣️如果需要讲NSDate转换为NSString,调用NSDateFormatter的stringFromDate: 方法执行格式化即可;如果需要讲NSString转换为NSDate,调用NSDateFormatter的dateFromString: 方法执行格式化即可。
示例代码:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
//需要被格式化的时间
//获取从1970年1月1日开始,20年之后的日期
NSDate* dt = [NSDate dateWithTimeIntervalSince1970: 3600*24*366*20];
//创建两个NSLocale,分别代表中国,美国
NSLocale* locales[] = {
[[NSLocale alloc]initWithLocaleIdentifier: @"zh_CN"],
[[NSLocale alloc]initWithLocaleIdentifier: @"en_US"]
};
NSDateFormatter* df[8];
//为上面两个NSLocale创建8个DateFormat对象
for(int i = 0; i < 2; i++)
{
df[i * 4] = [[NSDateFormatter alloc]init];
//设置NSDateFormatter的日期,时间风格
[df[i * 4] setDateStyle: NSDateFormatterShortStyle];
[df[i * 4] setTimeStyle: NSDateFormatterShortStyle];
//设置NSDateFormatter的NSLocale
[df[i * 4] setLocale: locales[i]];
df[i * 4 + 1] = [[NSDateFormatter alloc] init];
//设置NSDateFormatter的日期,时间风格
[df[i * 4 + 1] setDateStyle: NSDateFormatterMediumStyle];
[df[i * 4 + 1] setTimeStyle: NSDateFormatterMediumStyle];
//设置NSDateFormatter的NSLocale
[df[i * 4 + 1] setLocale: locales[i]];
df[i * 4 + 2] = [[NSDateFormatter alloc] init];
//设置NSDateFormatter的日期,时间风格
[df[i * 4 + 2] setDateStyle: NSDateFormatterLongStyle];
[df[i * 4 + 2] setTimeStyle: NSDateFormatterLongStyle];
//设置NSDateFormatter的NSLocale
[df[i * 4 + 2] setLocale: locales[i]];
df[i * 4 + 3] = [[NSDateFormatter alloc]init];
//设置NSDateFormatter的日期,时间风格
[df[i * 4 + 3] setDateStyle: NSDateFormatterFullStyle];
[df[i * 4 + 3] setTimeStyle: NSDateFormatterFullStyle];
//设置NSDateFormatter的NSLocale
[df[i * 4 + 3] setLocale: locales[i]];
}
for(int i = 0; i < 2; i++)
{
switch (i)
{
case 0: NSLog(@"-----------------------中国日期格式--------------------------"); break;
case 1: NSLog(@"-----------------------美国日期格式--------------------------"); break;
}
NSLog(@"SHORT格式的日期格式: %@", [df[i * 4] stringFromDate: dt]);
NSLog(@"MEDIUM格式的日期格式: %@",[df[i * 4 + 1] stringFromDate: dt]);
NSLog(@"LONG格式的日期格式: %@", [df[i * 4 + 2] stringFromDate: dt]);
NSLog(@"FULL格式的日期格式: %@", [df[i * 4 + 3] stringFromDate: dt]);
}
NSLog(@"\n\n\n\n\n");
NSDateFormatter* df2 = [[NSDateFormatter alloc] init];
//设置自定义的格式器模板
[df2 setDateFormat: @"公元yyyy年MM月DD日 HH时mm分"];
//执行格式化
NSLog(@"%@", [df2 stringFromDate: dt]);
NSString* dateStr = @"2013-03-02";
NSDateFormatter* df3 = [[NSDateFormatter alloc] init];
//根据日期字符串的格式设置格式模板
[df3 setDateFormat: @"yyyy-MM-dd"];
//将字符串转换为NSDate对象
NSDate* date2 = [df3 dateFromString: dateStr];
NSLog(@"%@", date2);
}
return 0;
}