1

给定一个任意日期,我需要找到该月下一周第一天的日期。请注意,它并不像在当前日期上增加 7 天那么简单,因为该月的最后一周可能少于 7 天。这是我现在使用的代码:

    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:NSWeekOfMonthCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit fromDate:currentDate];

    NSLog(@"week of month: %ld", [components weekOfMonth]);

    [components setWeekOfMonth:[components weekOfMonth] + 1];
    NSLog(@"new week of month: %ld", [components weekOfMonth]); //week of month is now 2

    [components setWeekday:1];
    NSDate *nextWeek = [calendar dateFromComponents:components];

例如,currentDate 设置为 2012-10-01。在此示例中,nextWeek 始终为 2012-10-01。似乎发送setWeekOfMonth:不会增加NSDateComponents对象中的其他日期组件。我是否配置了错误的日期组件,或者setWeekOfMonth:不应该那样工作?

4

2 回答 2

8

所以....让我们从 anNSDate和 an开始NSCalendar

NSDate *date = ...;
NSCalendar *cal = [NSCalendar currentCalendar];

找出该日期是星期几:

NSInteger weekdayOfDate = [cal ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date];
NSInteger numberOfDaysToStartOfCurrentWeek = weekdayOfDate - 1;

让我们将该日期移至下周:

NSDateComponents *oneWeek = [[NSDateComponents alloc] init];
[oneWeek setWeek:1]; // add one week
[oneWeek setDay:-numberOfDaysToStartOfCurrentWeek]; // ... and subtract a couple of days to get the first day of the week
NSDate *startOfNextWeek = [cal dateByAddingComponents:oneWeek toDate:date options:0];

此时,您的日期指向下周的第一天。现在我们应该验证它是否仍然在同一个月:

NSDateComponents *monthOfNextWeek = [cal components:NSMonthCalendarUnit fromDate:startOfNextWeek];
NSDateComponents *monthOfThisWeek = [cal components:NSMonthCalendarUnit fromDate:date];
if ([monthOfNextWeek month] != [monthOfThisWeek month]) {
  // the first day of the next week is not in the same month as the start date
}

当我运行这个时,我知道下周的开始是 2012 年 12 月 30 日(星期日,因为我的日历周从星期日开始)。

但是,如果我希望一周的第一天从星期一开始,我可以在这段代码前面加上:

[cal setFirstWeekday:2]; // the first day of the week is the second day (ie, Monday, because Sunday = 1)

如果我这样做,那么startOfNextWeek结果将在 2012 年 12 月 31 日。

于 2012-12-27T16:11:49.207 回答
0

这将是一个有效的答案:

NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"EEE"];

NSDate *date=[NSDate date];
NSString *dateString=[dateFormatter stringFromDate:date];

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [NSDateComponents new];

[calendar setFirstWeekday:1];//1 for Mon

NSDate *newDate=date;

while (![dateString isEqualToString:@"Mon"]) {
    components.day = 1;
    newDate = [calendar dateByAddingComponents:components toDate:newDate options:0];
    dateString=[dateFormatter stringFromDate:newDate];
}
NSLog(@"Upcoming week Date=%@",newDate);
于 2012-12-28T07:09:37.363 回答