场景:
我有示出的费用清单与所述类别和金额和日期沿着费用追踪iOS应用与我从费用明细视图控制器到一个表视图(与读取的结果控制器)存储费用。 我有我的实体“钱”,这是任何费用或收入父实体日期属性。
题:
我想要的是基本分类按月我的费用,并显示其为分节标题标题,例如:(11月1日日 - 11月30,2012),它显示的费用金额,并按照特定的月份相关的东西。 在该视图中提供了两个按钮,如果我会按右边的按钮,它会通过一个月(12月1日至十二月31日,2012)增加的月份,同样左键将通过每月递减一个月。
我将如何实现这一目标? 我想下面的代码 - 这是有点儿工作。 假设我有我的当前节头部为(Nov1 - 二〇一二年十一月三十〇日),当我按下左键,它给我的节头(10月1日至10月30日,2012)这是不对的,应该是2012年10月31日而不是2012年10月30日。
- (NSDate *)firstDateOfTheMonth
{
self.startDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:self.startDate];
[components setDay:1];
firstDateOfTheMonth = [[calendar dateFromComponents:components] retain];
return firstDateOfTheMonth;
}
- (NSDate *)lastDateOfTheMonth
{
NSCalendar* calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:firstDateOfTheMonth];
[components setMonth:[components month]+1];
[components setDay:0];
lastDateOfTheMonth = [[calendar dateFromComponents:components] retain];
return lastDateOfTheMonth;
}
然后,我有一个名为“monthCalculation”在我称之为上述两种方法的方法。
- (void)monthCalculation
{
[self firstDateOfTheMonth];
[self lastDateOfTheMonth];
}
现在下面的代码时,我按下左键(递减由一个月月):
- (IBAction)showPreviousDates:(id)sender
{
[self monthCalculation];
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setMonth:-1];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheMonth options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheMonth options:0];
self.startDate = newDate1;
self.endDate = newDate2;
NSLog(@" self start date in previous mode =%@", self.startDate);
NSLog(@" self end date in previous mode =%@", self.endDate);
}
下面的代码时,我按右边的按钮(递增由一个月月):
- (IBAction)showNextDates:(id)sender
{
[self monthCalculation];
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setMonth:1];
NSDate *newDate1 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:firstDateOfTheMonth options:0];
NSDate *newDate2 = [[NSCalendar currentCalendar]
dateByAddingComponents:dateComponents
toDate:lastDateOfTheMonth options:0];
self.startDate = newDate1;
self.endDate = newDate2;
NSLog(@" self start date in previous mode =%@", self.startDate);
NSLog(@" self end date in previous mode =%@", self.endDate);
}
我这样做对吗? 或者有更好的方法来做到实现这一目标? 任何帮助将不胜感激。