如何在所有情况下从 NSDate 获得正确的年份?
Posted
技术标签:
【中文标题】如何在所有情况下从 NSDate 获得正确的年份?【英文标题】:How to get the correct year from NSDate in all circumstances? 【发布时间】:2016-04-01 09:20:55 【问题描述】:我知道NSDateComponents
,但问题是当日期在一年的开头或结尾时,某种基于周的机制会弄乱结果。
例如:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit calendarUnit = NSYearCalendarUnit;
NSDateComponents *dateComponents = [calendar components:calendarUnit fromDate:self.date];
(lldb) po self.date
2015-12-31 16:00:00 +0000
(lldb) po dateComponents
<NSDateComponents: 0x12f4c83f0>
Calendar Year: 2016
更改minimumDaysInFirstWeek
也没有太大区别,NSDateFormatter
似乎也不是更好的方法。
【问题讨论】:
您的时区是多少。你是 >+8:00 吗? @Larme yes (lldb) po [[NSCalendar currentCalendar] timeZone] Asia/Shanghai (GMT+8) offset 28800 【参考方案1】:正如@Larme 在他的评论中指出的那样,您的本地时区正在影响您的结果;
您已指定 2015 年 12 月 31 日 UTC 下午 4 点。这是您当地时区 (UTC+8) 的 2016 年 1 月 1 日午夜。
您可以使用NSCalendar
方法componentsInTimeZone
来获取特定时区的年份:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSTimeZone *tz=[NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *dateComponents = [calendar componentsInTimeZone:tz fromDate:self.date];
int year=dateComponents.year; // This will be 2015
【讨论】:
【参考方案2】:您的代码非常好。 po
命令显示依赖于UTC
的时间描述,而NSCalendar
/ NSDateComponents
考虑当前时区。
2015-12-31 16:00:00 +0000
和
2016-01-01 00:00:00 +0800
都是同一时刻。
如果您必须始终处理基于 UTC 的日期,请将 NSCalendar
实例的时区设置为 UTC
。
【讨论】:
【参考方案3】:“年”组件将始终返回正确的年份 - 基于正在使用的日历! NSDate 以 UTC 记录,但年份是使用您当地的时区计算的。您给出的日期是 2015 年在伦敦使用 GMT(接近 UTC),但在 2016 年在世界其他地区。比如在澳大利亚,那个时候的新年烟花早就放了。
当您查看日历周时,这是一个完全不同且完全不相关的主题。 12 月 31 日可以是一年的最后一周,也可以是下一周的第一周。但这不是由“年”返回的。它由“yearForWeekOfYear”返回。
【讨论】:
以上是关于如何在所有情况下从 NSDate 获得正确的年份?的主要内容,如果未能解决你的问题,请参考以下文章