Search code examples
iosobjective-ccocoa-touchnsdate

Current Week Start and End Date


I want to get the current week start and end date and I also want to use the previous week start and end date and next week of the start and end date in current month.

Thanks in Advance.


Solution

  • I solve the problem thanks for Support

    Code :- it give the current week start and end date.

     NSDate *today = [NSDate date];
     NSLog(@"Today date is %@",today);
     dateFormat = [[NSDateFormatter alloc] init];
     [dateFormat setDateFormat:@"yyyy-MM-dd"];// you can use your format.
    
     //Week Start Date 
    
     NSCalendar *gregorian = [[NSCalendar alloc]        initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
    
    int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
    
    [components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
    [dateFormat_first setDateFormat:@"yyyy-MM-dd"];
    dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
    
    weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain];
    
    NSLog(@"%@",weekstartPrev);
    
    
    //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];
      NSLog(@"%@",weekEndPrev);