1

please have a look to following lines of code:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger weekNumber =  [[calendar components: NSWeekCalendarUnit fromDate:date] week];

now how we can get the first and last day of the given week number (assume that the week starts from monday to sunday).

also if it possible to get the array of all the dates belongs to the same week number.

Sumit Patel
  • 2,547
  • 8
  • 33
  • 45

1 Answers1

1

To get the first day of the week the following code can be used.

    NSDate *now = [NSDate date];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger weekNumber =  [[calendar components: NSWeekCalendarUnit fromDate:now] week];

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

    NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
    [comp setWeek:weekNumber];  //Week number.
    [comp setWeekday:1]; //First day of the week. Change it to 7 to get the last date of the week

    NSDate *resultDate = [gregorian dateFromComponents:comp];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM d, yyyy"];

    NSString *myDateString = [formatter stringFromDate:resultDate];
    NSLog(@"%@",myDateString);

as commented in the above code change the parameter of setWeekday method to 7 to get the last day of the week.

Once u have the first day and last day of the week u can get all the dates as mentioned in the below link. Array for dates between two dates

Note: The week starts from Monday for the region setting UK.

To change the iPhone Calendar to show Monday as the first day of the week. 1. tap "Settings" 2. tap "General" 3. tap "International" 4. tap "Region Format" 5. select "united kingdom"

Community
  • 1
  • 1
iCoder
  • 1,645
  • 1
  • 15
  • 23