创建 1 月 1 日和 2 日的 NSDate 时的奇怪行为

发布于 2024-09-06 09:20:12 字数 879 浏览 2 评论 0原文

我正在创建这样的日期:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY"];
NSInteger year = [[dateFormatter stringFromDate:[NSDate date]] intValue];
NSLog(@"NSInteger YEAR : %d\n", year);

//minutes, hours, day and month are initialized elsewhere...

NSDateComponents *comps = [[NSDateComponents alloc] init];      
[comps setYear:year];
[comps setMonth:month];
[comps setDay:day];
[comps setHour:hours];
[comps setMinute:minutes];
NSDate *sampleDate = [gregorian dateFromComponents:comps];

NSLog(@"sampleDate YEAR : %d\n", [[dateFormatter stringFromDate:sampleDate] intValue]);

我的问题是,当日期是 1 月 1 日或 1 月 2 日时,年份不正确。这里应该是 2010 年(因为我检索今天的年份),但实际上是 2009 年。 。我不明白为什么!这种情况只发生在这两天...

你知道为什么会这样吗? 先感谢您。

I'm creating a date like this :

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY"];
NSInteger year = [[dateFormatter stringFromDate:[NSDate date]] intValue];
NSLog(@"NSInteger YEAR : %d\n", year);

//minutes, hours, day and month are initialized elsewhere...

NSDateComponents *comps = [[NSDateComponents alloc] init];      
[comps setYear:year];
[comps setMonth:month];
[comps setDay:day];
[comps setHour:hours];
[comps setMinute:minutes];
NSDate *sampleDate = [gregorian dateFromComponents:comps];

NSLog(@"sampleDate YEAR : %d\n", [[dateFormatter stringFromDate:sampleDate] intValue]);

My problem is that when the date is January 1st or January 2nd, the year is not correct.. Here it should be 2010 (as I retrieve today's year), but actually it is 2009... I don't understand why ! And this is only happening for those 2 days...

Do you have any idea why is it that way ?
Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倾城月光淡如水﹏ 2024-09-13 09:20:12

请参阅 Unicode 标准。 “yyyy”(小写)为您提供年份,但“YYYY”(大写)为您提供该日期所在周的年份(也就是说,如果该日期在去年的第 52 周内,则 YYYY 将是去年)。

See the Unicode standard. "yyyy" (lower case) gives you the year, but "YYYY" (upper case) gives you the year for the date's week (that is, if the date is within the 52nd week of the last year, YYYY will be last year).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文