1

我正在寻找一种方法来获取从今天起过去六个月的清单。

今天是五月,所以我会寻找以下输出:

May 2013,
Apr 2013,
Mar 2013,
Feb 2013,
Jan 2013,
Dec 2012

我知道这将与NSDateComponents,但我找不到任何帮助。

4

2 回答 2

2

试试这个,你可以int i根据你的选择改变值

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];

for (int i = 0; i <=6 ;i++) {
    [offsetComponents setMonth:-i];

    NSDate *dateStr = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM YYYY"];
    NSString *stringFromDate = [formatter stringFromDate:dateStr];
    NSLog(@"%@", stringFromDate);
}
于 2013-05-16T12:15:14.797 回答
1

我建议将MTDates与以下内容一起使用:

[[NSDate date] mt_dateMonthsBefore:1];
[[NSDate date] mt_dateMonthsBefore:2];
[[NSDate date] mt_dateMonthsBefore:3];
[[NSDate date] mt_dateMonthsBefore:4];
[[NSDate date] mt_dateMonthsBefore:5];
[[NSDate date] mt_dateMonthsBefore:6];
于 2013-05-16T11:59:50.737 回答