Scenario:
I have an expense tracking iOS Application and I am storing expenses from a expense detail view controller into a table view (with fetched results controll
Here are some methods that should do what you want:
First, in your viewDidLoad method add:
self.startDate = [NSDate date];
[self updateDateRange];
This gives you a starting point. Then, I added the following five methods (Note: previousMonthButtonPressed
/nextMonthButtonPressed
should be wired up to your buttons):
// Return the first day of the month for the month that 'date' falls in:
- (NSDate *)firstDayOfMonthForDate:(NSDate *)date
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:date];
comps.day = 1;
return [cal dateFromComponents:comps];
}
// Return the last day of the month for the month that 'date' falls in:
- (NSDate *)lastDayOfMonthForDate:(NSDate *)date
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:date];
comps.month += 1;
comps.day = 0;
return [cal dateFromComponents:comps];
}
// Move the start date back one month
- (IBAction)previousMonthButtonPressed:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:self.startDate];
comps.month -= 1;
self.startDate = [cal dateFromComponents:comps];
[self updateDateRange];
}
// Move the start date forward one month
- (IBAction)nextMonthButtonPressed:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:self.startDate];
comps.month += 1;
self.startDate = [cal dateFromComponents:comps];
[self updateDateRange];
}
// Print the new range of dates.
- (void)updateDateRange
{
NSLog(@"First day of month: %@", [self firstDayOfMonthForDate:self.startDate]);
NSLog(@"Last day of month: %@", [self lastDayOfMonthForDate:self.startDate]);
}
Try this:
- (NSDate *)lastDateOfTheMonth
{
NSCalendar* calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:firstDateOfTheMonth];
[components setMonth:[components month]+1];
NSDateComponents* offset = [[[NSDateComponents alloc] init] retain];
[offset setDay:-1];
lastDateOfTheMonth = [[calendar dateByAddingComponents:offset toDate:[components date] options:0] retain];
return lastDateOfTheMonth;
}