iPhone下周的最后一个日期

时间:2012-09-17 11:00:26

标签: iphone nsdate nscalendar

我想要下周的最后一天。这是我用的代码..

NSCalendar *gregorian11 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
NSDateComponents *components1 = [gregorian11 components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today1];
[components1 setDay:([components1 day]-([components1 weekday]-1)+14)];

NSDate *lastdayOfNextWeek = [gregorian11 dateFromComponents:components1];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:@"dd/MM/yyyy :EEEE"];
NSString *dateString_first = [dateFormat_first stringFromDate:beginningOfWeek1];

NSLog(@"last_date: %@", dateString_first);

输出:last_date: 30/09/2012 :Sunday

现在,我想知道这是正确的方法,还是你们有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

Hey Check out this Code.....:)


 //Week End Date

    NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];

    int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week

    [componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week

    NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
    NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
    [dateFormat_End setDateFormat:@"yyyy-MM-dd"];
    dateEndPrev = [dateFormat stringFromDate:EndOfWeek];

    weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain];

    //Convert the nsdate to nsstirng for Query

    strWeekEndQuery =[dateFormat stringFromDate:weekEndPrev];
    NSLog(@"%@",strWeekEndQuery);