1

如何获得约会的一周的第一天

这似乎更容易,因为:

  • 当星期从星期天开始时,我需要取回星期天的日期
  • 如果它从星期一开始,我需要得到星期一的日期

输入日期是一周中的任何日期...我尝试了几种方法,但边缘情况使它变得困难

我做了一个函数,但是不能 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];

}
4

1 回答 1

7

使用日历方法更容易rangeOfUnit,它根据当前的语言环境正确处理“一周的开始”:

NSDate *date = your date;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startOfWeek;
[calendar rangeOfUnit:NSWeekOfYearCalendarUnit
            startDate:&startOfWeek
             interval:NULL
              forDate:date];

使用NSDateComponents,它将按如下方式工作(假设一周有 7 天):

NSDate *date = your date;
NSDateComponents *comp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit
                                     fromDate:date];
NSDate *startOfDay = [calendar dateFromComponents:comp];
NSInteger diff = (NSInteger)[calendar firstWeekday] - (NSInteger)[comp weekday];
if (diff > 0)
    diff -= 7;
NSDateComponents *subtract = [[NSDateComponents alloc] init];
[subtract setDay:diff];
NSDate *startOfWeek = [calendar dateByAddingComponents:subtract toDate:startOfDay options:0];
于 2013-06-01T20:16:21.000 回答