在IOS SDK中获取周日期

use*_*811 1 calendar nscalendar ios

我想通过日期名称获取当前和下周的日期.

即如果今天的日期是28-06-2013(星期五),那么我想把这个日期从2013年6月23日(周日)到29-06-2013(星期六).

对于下周, 我希望从2013年6月30日(星期日)到2013年7月6日(星期六)获取日期.

我怎样才能做到这一点?

谢谢,

Mic*_*gar 12

下面是示例代码.

-(NSArray*)daysThisWeek
{
     return  [self daysInWeek:0 fromDate:[NSDate date]];
}

-(NSArray*)daysNextWeek
{
    return  [self daysInWeek:1 fromDate:[NSDate date]];
}
-(NSArray*)daysInWeek:(int)weekOffset fromDate:(NSDate*)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];

    //ask for current week
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    comps=[calendar components:NSWeekCalendarUnit|NSYearCalendarUnit fromDate:date];
    //create date on week start
    NSDate* weekstart=[calendar dateFromComponents:comps];
    if (weekOffset>0) {
        NSDateComponents* moveWeeks=[[NSDateComponents alloc] init];
        moveWeeks.week=1;
        weekstart=[calendar dateByAddingComponents:moveWeeks toDate:weekstart options:0];
    }

    //add 7 days
    NSMutableArray* week=[NSMutableArray arrayWithCapacity:7];
    for (int i=1; i<=7; i++) {
        NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
        compsToAdd.day=i;
        NSDate *nextDate = [calendar dateByAddingComponents:compsToAdd toDate:weekstart options:0];
        [week addObject:nextDate];

    }
    return [NSArray arrayWithArray:week];
}
Run Code Online (Sandbox Code Playgroud)