如何获得约会的一周的第一天
这似乎更容易,因为:
- 当星期从星期天开始时,我需要取回星期天的日期
- 如果它从星期一开始,我需要得到星期一的日期
输入日期是一周中的任何日期...我尝试了几种方法,但边缘情况使它变得困难
我做了一个函数,但是不能 100% 工作(不确定 [components setDay: -weekday + 2];)
- (NSDate *)firstDateOfWeek {
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
// because sunday is 0, we need it to be 6
NSInteger weekday = (([weekdayComponents weekday] + 6) % 7);
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
[components setDay: -weekday + 2];
return [calendar dateFromComponents:components];
}