iOS 获取当前时间使用dateformatter出错?

以前没问题 最近才出来

NSDate *now1 = [NSDate date];

NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];

[dateformatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

NSString *locationString= [dateformatter stringFromDate:now1];

now1 得到时间是当前年份2015 loactionString 得到却是2016年

解决方法就是:把YYYY改成小写就好了

原因就是:DateFormatter 查了一下class reference,具体描述:

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.

就是说yyyy指定的是“日历年”,YYYY指定的是“星期年”,具体什么是日历年星期年的没去再找是什么,但打开日历似乎就明白了。所以日后注意DateFormatter里面的年份,你不会想用YYYY的~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容