我想根据当前日期计算NSDate对象。如果当前日期为2015年4月1日,则需要生成日期2014年12月31日。如果当前日期为2015年4月30日,则仍需要生成日期2014年12月31日。但是,如果它是2015年5月1日,我需要生成2015年1月31日。换句话说,无论我在哪个月,我都需要从四个月前开始的月底的日期,而不管我在当月的位置。鉴于NSDate,找到第四个前个月的最后一天
我迄今的代码是:
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
[dayComponent setDay:-90];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];
NSLog(@"The date I am getting is: %@", nextDate);
上面的代码给了我之前的当前日期正好是90天的日期值,但我需要的日期始终是月底那是4个月前。
你检查出[YLMoment](https://github.com/yannickl/YLMoment)?我敢打赌,它会帮助你做你需要的。 – brandonscript 2015-02-24 21:11:27
你知道,月底是下个月开始的前一天。除了天以外还有其他组件。而NSCalendar'rangeOfUnit'可以提供一些有用的信息。 – 2015-02-24 21:50:16