如何从周数和年份获取日期

时间:2013-07-03 13:50:02

标签: ios objective-c nsdate

我想从周数和年份获取日期。我从服务器获得周数和年份。我是   尝试下面的代码,但它不会工作。

 NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter2 setDateFormat:@"yyyy-MM-dd"];

NSDate *now = [dateFormatter2 dateFromString:@"2001-01-01"];
NSCalendar *gregorian1 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps1 = [gregorian1 components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:now];


[comps1 setYear:2013];
[comps1 setWeek:51];
[comps1 setWeekday:2];

NSDate *resultDate = [gregorian1 dateFromComponents:comps1];

输出为: - 2012-12-31 18:30:00 +0000

我在做错了什么?提前谢谢..

2 个答案:

答案 0 :(得分:5)

您的问题是您的NSDateComponents对象中有不明确的组件,因为您是从现有NSDate创建的组件。在代码中放置一个断点并查看comps1

(lldb) po comps1
$0 = 0x0ab354f0 <NSDateComponents: 0xab354f0>
    Calendar Year: 2013
    Month: 1
    Leap month: no
    Day: 1
    Week (obsolescent): 51
    Weekday: 2

在第51周的星期一创造一个日期很难,即同一时间的1月1日。

如果要使用NSDateComponents创建NSDate,则应从“新鲜”组件开始。像这样:

NSCalendar *gregorian1 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps1 = [[NSDateComponents alloc] init];

[comps1 setYear:2013];
[comps1 setWeek:51];
[comps1 setWeekday:2];

NSDate *resultDate = [gregorian1 dateFromComponents:comps1];

结果:2013-12-16(希望是你所期待的)

分配组件的代码具有以下组件:

(lldb) po comps1
$0 = 0x0a37d220 <NSDateComponents: 0xa37d220>
    Calendar Year: 2013
    Leap month: no
    Week (obsolescent): 51
    Weekday: 2

没有歧义。

此外,用[comps1 setWeek:51];替换[comps1 setWeekOfYear:51];是个好主意但是你的主要问题是重用现有的NSDateComponents对象。

答案 1 :(得分:2)

我得到了解决方案

  NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter2 setDateFormat:@"yyyy-MM-dd"];

NSDate *now = [dateFormatter2 dateFromString:@"2001-01-01"];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
gregorian.firstWeekday = 2; // Sunday = 1, Saturday = 7

NSDateComponents *components = [gregorian components:NSYearCalendarUnit |NSWeekdayCalendarUnit fromDate:now];
[components setYear:2013];
[components setWeekOfYear:18];
[components setWeekday:2];

NSDate *resultDate = [gregorian dateFromComponents:components];

输出为: - 2013-04-28 18:30:00 +0000