创建 1 月 1 日和 2 日的 NSDate 时的奇怪行为
我正在创建这样的日期:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅 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).