NSCalendar dateFromComponents返回错误的日期为2 [英] NSCalendar dateFromComponents returns wrong date by 2

查看:259
本文介绍了NSCalendar dateFromComponents返回错误的日期为2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一年中第一周嘴的日期:

I want to find out the date of the first week of a mouth in a year:

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日历我需要得到是:

And when I compare to my mac calendar what I need to get is:

2012-12-31 23:00:00 +0000

有任何建议吗?

推荐答案

问题可能是设置 weekDay
这里是工作代码

Problem might be setting the weekDay here is the working code

 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

other alternate you could use NSGregorianCalendar, instead of 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

这篇关于NSCalendar dateFromComponents返回错误的日期为2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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