Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate get previous week, previous month issue

Tags:

ios

nsdate

I need to get previous week and month from current date.

So I found solution that can recalculate current date adding interval

- dateByAddingTimeInterval

And this params for it:

[[NSDate date] dateByAddingTimeInterval: -604800.0] (for getting previous week)

[[NSDate date] dateByAddingTimeInterval: -2629743.83] (for getting previous month)

As I think for getting week this method works good without any problem, because each week has seven days and interval doesn't change. But for month we have a problem because each month has different number of days.

like image 342
Matrosov Oleksandr Avatar asked Mar 25 '13 09:03

Matrosov Oleksandr


1 Answers

Using NSDateComponents it would be easy and accurate

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.month = -1;
comps.day   = -1;
NSDate *date = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date]; // Get necessary date components
NSLog(@"Previous month: %d",[components month]);
NSLog(@"Previous day  : %d",[components day]);
like image 192
βhargavḯ Avatar answered Nov 15 '22 21:11

βhargavḯ