从日历目标c获取最后一个星期一

时间:2018-01-05 11:22:22

标签: ios objective-c nscalendar

我需要从今天开始查看上一个星期一的日期,但是下面的代码失败了......即如果尝试2018年1月5日,我无法获得2018年1月1日..你能告诉我这是什么错误吗?提前谢谢。

NSDateComponents *dateComponent;
dateComponent = [calendar components:(NSWeekOfYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]]; // Jan 5 2018


NSDateComponents *components = [NSDateComponents new];
components.weekday = 2;
components.weekOfYear = dateComponent.weekOfYear;
components.year = dateComponent.year;
NSDate *dateStart = [[NSCalendar currentCalendar] dateFromComponents: components];
NSLog(@"last monday is : %@", dateStart) //last monday is : 2018-12-31

1 个答案:

答案 0 :(得分:1)

nextDateAfterDate:matchingUnit:value:options:的专用方法NSCalendar可以提供您想要的内容。

只需使用NSCalendarUnitWeekday 2传递value并向后搜索

NSDate *dateStart = [[NSCalendar currentCalendar] nextDateAfterDate:[NSDate date] 
                                                       matchingUnit: NSCalendarUnitWeekday 
                                                              value: 2
                                                            options:NSCalendarSearchBackwards | NSCalendarMatchNextTime];
NSLog(@"last monday is : %@", dateStart); //last monday is : 2018-01-01