0

我需要制作一个日历,用户可以在其中滚动几周。一周的第一天和最后一天将显示为(例如)“6 月 4 日 - 6 月 10 日”。

现在我从一开始就知道我需要NSDateand NSCalendar,实际上我设法得到了这周的第一天和最后一天,但它看起来非常麻烦,我相信需要一个更简单的方法,因为我需要获取未来几周和过去几周的日期。这是我的代码,它给出了本周的第一天和最后一天的和daymonth

    NSDate *today = [NSDate date];
    NSCalendar* cal = [NSCalendar currentCalendar];
    NSDateComponents* comp = [cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSYearCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit) fromDate:[NSDate date]];

    NSDate *beginOfWeek = [today dateByAddingTimeInterval: -1*([comp weekday]-2)*24*3600];
    NSDate *endOfWeek = [today dateByAddingTimeInterval:(7-[comp weekday]+2)*24*3600];

    NSLog(@"beginWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] day]);
    NSLog(@"endWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] day]);
    NSLog(@"beginWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] month]);
    NSLog(@"endWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] month]);
4

1 回答 1

1

我发现了这个,可能对你有帮助:http: //www.cocoanetics.com/2009/11/add-one-week-skip-weekend/

- (NSDate *)addWeekToDateAndSkipWeekend:(NSDate *)now {
int daysToAdd = 6; // we'll add the 7th later

// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];

// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDate *newDate = [gregorian dateByAddingComponents:components toDate:now options:0];

[components setDay:1]; // reuse to skip single days
NSDateComponents *newDateComps; // new componets to get weekday

// do always executed once, so we add the 7th day here
do
{
    // add one day
    newDate = [gregorian dateByAddingComponents:components toDate:newDate options:0];
    newDateComps = [gregorian components:NSWeekdayCalendarUnit fromDate:newDate];

    // repeat if the date is Saturday (7) or Sunday (1)
    NSLog(@"weekday: %d", [newDateComps weekday]);
} while (([newDateComps weekday]==7)||([newDateComps weekday]==1));

return newDate;
}

从理论上讲,您在带有 [NSDate date] 的 for 循环中运行它,您将获得7th返回的日期,然后您将通过此运行返回的7th日期并获得下一个......等等。

可能需要稍作改动,如果您不需要它,请删除周六+周日的检查。

希望这可以帮助 !

于 2012-06-08T12:00:07.927 回答