NSCalendar dateFromComponents返回错误的日期2
我想找出一年内第一周口的日期:
NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; [components setYear:2013]; [components setMonth:1]; [components setWeekOfMonth:1]; [components setWeekday:1]; NSDate *newDate = [calendar dateFromComponents:components]; NSLog(@"%@",newDate);
我得到的是:
2012-12-29 23:00:00 +0000
当我与我的Mac日历比较时,我需要得到的是:
2012-12-31 23:00:00 +0000
有什么建议么?
问题可能是设置weekDay
这里是工作代码
NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; [components setYear:2013]; [components setMonth:1]; [components setDay:1]; NSDate *newDate = [calendar dateFromComponents:components]; NSLog(@"%@",newDate); //2012-12-31 23:00:00 +0000
其他替代你可以使用NSGregorianCalendar
,而不是currentCalender
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]]; [comp setYear:2013]; [comp setMonth:1]; [comp setDay:1]; NSDate *firstDayOfMonthDate = [gregorian dateFromComponents:comp]; NSLog(@"%@",firstDayOfMonthDate); // 2012-12-31 23:00:00 +0000
(我意识到你现在已经知道发生了什么,但为了未来的读者……)
看看你在这做什么:
NSDateComponents *components = [[NSDateComponents alloc] init]; [components setYear:2013]; [components setMonth:1]; [components setWeekOfMonth:1]; [components setWeekday:1];
让我们今天(2013年2月28日)作为一个例子,看看我们在每一步之后得到了什么(假设我不能检查这个!):
-
setYear:2013
– 没有变化,因为这一年已经是2013年 -
setMonth:1
– 更改为1月:2013-01-28 -
setWeekOfMonth:1
– 更改为2013年1月第一周的同一天(星期四):2013-01-03 -
setWeekday:1
– 在同一周更改为星期日:2012-12-30
现在当你打印出2012-12-30的当地午夜时,但是在UTC中,你得到的是“2012-12-29 23:00:00 +0000”,因为你的本地时区可能比UTC提前1小时。
所以你已经建立了,你想要setDay
而不是setWeekOfMonth
/ setWeekday
,假设你真的想要“1月1日”而不是“1月1日的星期日”。