NSDateComponents 在 1970 年 1 月 1 日返回第 53 周
因此,当使用 NSCalendar 和 NSDateComponents 从 NSDate 对象中提取日期组件时,我遇到了一个奇怪的行为。 如果日期距离 1970 年 0 秒,周部分将返回 53。 除了模数 52 的明显方法之外,是否有对此的解释或解决方法?
这是您可以在计算机上运行来测试的代码:
-
(void)testDate {
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:0];
NSDateComponents *comp = [cal components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSWeekCalendarUnit) fromDate:date];
DLog(@"%d/%d/%d week: %d", [comp day],[comp month], [comp year], [comp week]);
}
这是输出:
31/12/1969 week: 53
(gdb) po date
1970-01-01 00:00:00 +0000
(gdb)
So when extracting the dates components from NSDate object using NSCalendar and NSDateComponents I encountered a weird behavior.
If the date is 0 sec from 1970 the week component will return 53.
Is there an explination for this or a way to fix other than the obvious way of modulus 52?
here is the code you can run on your machine to test:
-
(void)testDate {
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:0];
NSDateComponents *comp = [cal components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSWeekCalendarUnit) fromDate:date];
DLog(@"%d/%d/%d week: %d", [comp day],[comp month], [comp year], [comp week]);
}
and here is the output:
31/12/1969 week: 53
(gdb) po date
1970-01-01 00:00:00 +0000
(gdb)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我明白了,
所以我对你得到的结果有点惊讶,但我对
week: 53
结果为52 * 7 = 364
并不感到惊讶,我们一年有365天。为了实现这一点,我预计这一周会从 1969 年的星期日开始,但事实并非如此。Well I got this,
So I am bit surprised by the result you got but I am not that surprised that a
week: 53
turned up as52 * 7 = 364
and we've 365 days in a year. For that to happen I would expect the week to start on Sunday on 1969 but it didn't.我的朋友,你发现了闰周。几年前我在做一些 SQL 报告时遇到过这个问题。
You my friend have discovered the leap week. I have run across this doing some SQL reporting a couple years back.