如何在Objective-c中获得下周的开始和结束日期?

我已经尝试下周开始和结束日期,但是我已经获得了本周的开始和结束日期。如何在Objective-c中获得下周的开始和结束日期。如何在Objective-c中获得下周的开始和结束日期?

回答:

您可以使用下面的代码获得这个星期和下个星期的所有日期: -

NSArray * allDatesOfThisWeek = [self daysThisWeek]; 

NSArray * allDatesOfNextWeek = [self daysNextWeek];

以下方法用于计算该周的日期: -

-(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];

NSDateComponents* moveWeeks=[[NSDateComponents alloc] init];

moveWeeks.weekOfYear=weekOffset;

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];

}

如果你想从今天获得下周的日期,然后通过weekOffset = 2像这样: -

NSArray * allDatesOfNextToNextWeek = [self daysInWeek:2 fromDate:now]; 

如果你希望从今天获得前一周的日期,然后通过weekOffset = -1是这样的: -

NSArray * allDatesOfPreviousWeek = [self daysInWeek:-1 fromDate:now]; 

希望,这是你在找什么。任何担心都会回到我身上。

回答:

NSCalendar包含专用的方法来做到这一点,例如nextDateAfterDate:matchingUnit:value:options:dateByAddingComponents:toDate:options:

// Get the current calendar 

NSCalendar *calendar = [NSCalendar currentCalendar];

// Get the next occurrence for the first weekday of the current calendar

NSDate *startOfNextWeek = [calendar nextDateAfterDate:[NSDate date] matchingUnit:NSCalendarUnitWeekday value:calendar.firstWeekday options:NSCalendarMatchStrictly];

// Create new date components +7 days and -1 seconds

NSDateComponents *endOfNextWeekComponents = [[NSDateComponents alloc] init];

endOfNextWeekComponents.day = 7;

endOfNextWeekComponents.second = -1;

// Add the date components to the start date to get the end date.

NSDate *endOfNextWeek = [calendar dateByAddingComponents:endOfNextWeekComponents toDate:startOfNextWeek options:NSCalendarMatchStrictly];

NSLog(@"%@ - %@", startOfNextWeek, endOfNextWeek);

以上是 如何在Objective-c中获得下周的开始和结束日期? 的全部内容, 来源链接: utcz.com/qa/260900.html

回到顶部