3

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

 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

我究竟做错了什么 ?提前致谢..

4

2 回答 2

6

您的问题是您的 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(希望这是您所期望的)

alloc 初始化组件的代码具有以下组件:

(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 对象是一个好主意。

于 2013-07-03T14:32:16.973 回答
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

于 2013-07-03T14:13:31.660 回答