创建1月1日和2日的NSDate时的奇怪行为 [英] Weird behavior when creating an NSDate of January the 1st and the 2nd

查看:108
本文介绍了创建1月1日和2日的NSDate时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建这样的日期:

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]);

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

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.

推荐答案

参见 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).

这篇关于创建1月1日和2日的NSDate时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆