• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

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

objective-c 来源:reshma 17次浏览

我已经尝试下周开始和结束日期,但是我已经获得了本周的开始和结束日期。如何在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]; 

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


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)