如何在本月下周的第一天获得NSDate

时间:2012-12-27 06:39:33

标签: cocoa nsdate nscalendar nsdatecomponents

鉴于任意日期,我需要找到该月下一周第一天的日期。请注意,它并不像在当前日期添加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:不应该像那样工作?

2 个答案:

答案 0 :(得分:8)

所以....让我们从NSDateNSCalendar开始:

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日生成。

答案 1 :(得分: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);