tags:

views:

70

answers:

3

Hi, In my application I m using following codes to retrieve current date and day :-

NSDate *today1 = [NSDate date]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"dd/MM/yyyy :EEEE"]; NSString *dateString11 = [dateFormat stringFromDate:today1];

NSLog(@"date: %@", dateString11);
//[dateFormat release];
NSCalendar *gregorian11 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
NSDateComponents *components1 = [gregorian11 components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today1];
[components1 setDay:([components1 day]-([components1 weekday]-1))];

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

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

but using above code I only got the current day and Date and first day of week but I need to get last day of week.

Where I m wrong in my code and what modification is needed to get last day/date of week.

Please help me out its urgent.

Thanks a lot in advance

+2  A: 

Try this.

[components1 setDay:([components1 day]-([components1 weekday]-1) + 6)];

NSDate *endOfWeek1 = [gregorian11 dateFromComponents:components1];
kovpas
[components1 setDay:([components1 day]-([components1 weekday]-1) + 6)]; now =[gregorian dateFromComponents:components1]; [format setDateFormat:@"dd/MM/yyyy :EEEE"]; dateString = [format stringFromDate:now]; NSLog(@" week Last_date: %@", dateString);but above code output is== week Last_date: 29/04/2010 :Thursday
That's weird. You get the first day of week - this correct, but after you add 6 days to it, you get 4th day. Well, I'd suggest to add 9 instead of 6 - this should work.
kovpas
A: 

[components1 setDay:([components1 day]+([components1 weekday]+1))];

It will print

date: 27/04/2010 :Tuesday Weekend: 01/05/2010 :Saturday

I write "weekend" instead of First day....

Neelam Roy
A: 

If you have an NSDate, you can use the current NSCalendar to retrieve that date's NSDateComponents. Set the NSDateComponents's weekday to 1 (the first day of the week), create a copy, and set the copy's weekday to 7 (the last day of the week). Then use the NSCalendar to convert both the NSDateComponents back to their respective NSDate objects, after which you can use an NSDateFormatter to create your string representation.

This link has an example about how to get a date's weekday:

http://stackoverflow.com/questions/1057349#1057405

hAPPY cODING...

Suriya