Anu
Anu

Reputation: 89

objective-c how to get days of Previous week?

How can I get an array of days of previous week? For example - today is wed/04/2013, which is the forth day of week if first day of week is sunday. I need array with ' sunday/25/2013', mon/26/2013,..... sat/31/2013? i am doing this but it didn't work help required..

 NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *currentComps = [myCalendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:weekDate];
int ff = currentComps.weekOfYear;
NSLog(@"1  %d", ff);


[currentComps setDay:2]; // 1: sunday
[currentComps setWeek: [currentComps week] - 1];
NSLog(@"currentComps setWeek:>>>>>>  %@", currentComps);
NSDate *firstDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
NSLog(@"firstDayOfTheWeek>>>>>>  %@", firstDayOfTheWeek);
NSString *firstStr = [myDateFormatter stringFromDate:firstDayOfTheWeek];
lbl_Day1.text = firstStr;

Upvotes: 0

Views: 948

Answers (1)

Martin R
Martin R

Reputation: 539705

// Start with some date, e.g. now:
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];

// Compute beginning of current week:
NSDate *date;
[cal rangeOfUnit:NSWeekCalendarUnit startDate:&date interval:NULL forDate:now];

// Go back one week to get start of previous week:
NSDateComponents *comp1 = [[NSDateComponents alloc] init];
[comp1 setWeek:-1];
date = [cal dateByAddingComponents:comp1 toDate:date options:0];

// Some output format (adjust to your needs):
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"EEEE dd/MM/yyyy"];

// Repeatedly add one day:
NSDateComponents *comp2 = [[NSDateComponents alloc] init];
[comp2 setDay:1];
for (int i = 1; i <= 7; i++) {
    NSString *text = [fmt stringFromDate:date];
    NSLog(@"%@", text);
    date = [cal dateByAddingComponents:comp2 toDate:date options:0];

}

Output:

Sunday 25/08/2013
Monday 26/08/2013
Tuesday 27/08/2013
Wednesday 28/08/2013
Thursday 29/08/2013
Friday 30/08/2013
Saturday 31/08/2013

ADDED (in reply to you your comment):

NSDateComponents *comp2 = [[NSDateComponents alloc] init];
[comp2 setDay:1];

// First day:
lbl_Day1.text = [fmt stringFromDate:date];

// Second day:
date = [cal dateByAddingComponents:comp2 toDate:date options:0];
lbl_Day2.text = [fmt stringFromDate:date];

// Third day:
date = [cal dateByAddingComponents:comp2 toDate:date options:0];
lbl_Day3.text = [fmt stringFromDate:date];

// and so on ...

Upvotes: 4

Related Questions