NSDateFormatter
1.使用方法:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//显示 年 月 日 时 分 秒 星期 例:2013-10-08 20:58:29 星期二
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss EEEE"];
NSString *string = [formatter stringFromDate: [[NSDate alloc] init]];
2.setDateFormat方法
dateFormat
The date format string used by the receiver.
Declaration
@property(copy) NSString *dateFormat;
Discussion
See Data Formatting Guide for a list of the conversion specifiers permitted in date format strings.
You should only set this property when working with fixed format representations, as discussed in Working With Fixed Format Date Representations. For user-visible representations, you should use the dateStyle
and timeStyle
properties, or the setLocalizedDateFormatFromTemplate:
method if your desired format cannot be achieved using the predefined styles; both of these properties and this method provide a localized date representation appropriate for display to the user.
3.大小写YYYY的区别
It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.
PS:有英语好的大神的话请帮忙翻译一下,以下翻译来自于Google翻译
它使用yyyy指定年份组件。一个常见的错误是使用YYYY。yyyy指定日历年,而YYYY指定"ISO年-周日历"中使用的年(年中的周)。在大多数情况下,yyyy和yyyy产生相同的数字,但它们可能不同。通常,您应该使用日历年。
官方链接:Date Formatters
问题复现:
当前年份的最后一个月的最后一天可能显示成下一年的最后一个月的最后一天(实际上就是年份显示有问题。例:应该显示2021年,实际显示2022年)
4.NSDateFormatter格式汇总
4.1 正常显示
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss EEEE"];
2021-01-01 18:00:00 星期五
4.2 yyyy -> yy 年份只显示后两位
[dateFormatter setDateFormat:@"yy-MM-dd HH:mm:ss EEEE"];
21-01-01 18:00:00 星期五
4.3 MM -> M 和 dd -> d 当月份和日期是双数时正常显示,是单数时只显示一位数
[dateFormatter setDateFormat:@"yyyy-M-d HH:mm:ss EEEE"];
2021-1-1 18:00:00 星期五
4.4 dd -> DD 显示今天是今年的第几天
[dateFormatter setDateFormat:@"yyyy-MM-DD HH:mm:ss EEEE"];
2021-12-365 18:00:00 星期五
4.5 HH -> H 和 mm -> m 和 ss -> s 当时和分和秒是双数时正常显示,是单数时只显示一位数
[dateFormatter setDateFormat:@"yyyy-MM-dd H:m:s EEEE"];
2021-01-01 18:0:0 星期五
4.6 HH -> hh 时间从24小时制变为12小时制
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss EEEE"];
2021-01-01 06:00:00 星期五
4.7 加a,区分上午下午
[dateFormatter setDateFormat:@"yyyy-MM-dd a hh:mm:ss EEEE"];
2021-01-01 下午 06:00:00 星期五
4.8 EEEE -> EE 星期几遍为周几
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss EE"];
2021-01-01 18:00:00 周五
4.9 - -> / 中间的-分隔符变为/分隔符
[dateFormatter setDateFormat:@"yyyy/MM/dd a hh:mm:ss EE"];
2021/01/01 下午 06:00:00 周五
欢迎补充添加~~