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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With