我想从周数和年份获得日期.我从服务器获得周数和年份.我是 尝试下面的代码,但它不会工作. NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];// this is imporant - we set our input date format t
尝试下面的代码,但它不会工作.
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
我究竟做错了什么 ?提前致谢..
您的问题是您的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对象.