如何从周数和年份中获取日期
我想从周数和年份中获取日期.我从服务器获得了周数和年份.我是尝试以下代码,但它不起作用.
I want to get date from week number and year . i got week number and year from server . I am trying following code but it wont work.
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
Output is :- 2012-12-31 18:30:00 +0000
我做错了什么?提前致谢..
what am i doing wrong ? Thanks in advance..
您的问题是您的 NSDateComponents 对象中有不明确的组件,因为您从现有的 NSDate 创建了这些组件.在您的代码中放置一个断点并查看 comps1
:
Your problem is that you have ambiguous components in your NSDateComponents object, because you created the components from an existing NSDate. Put a breakpoint in your code and look at 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 日)同时创建一个日期有点困难.
It's kind of hard to create a date on monday in week 51 that is January, 1st at the same time.
当你想用 NSDateComponents 创建一个 NSDate 时,你应该从新鲜"组件开始.像这样:
When you want to create a NSDate with NSDateComponents you should start with "fresh" components. Like this:
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(希望是您所期望的)
Result: 2013-12-16 (which is hopefully what you expected)
alloc 初始化组件的代码具有以下组件:
The code that alloc inits the components has these components:
(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 对象.
Additionally it would be a good idea to replace [comps1 setWeek:51];
with [comps1 setWeekOfYear:51];
But your main problem was the reuse of an existing NSDateComponents object.