我需要从今天开始查看上一个星期一的日期,但是下面的代码失败了......即如果尝试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
答案 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