列出前六个月

时间:2013-05-16 11:47:01

标签: objective-c cocoa nsdatecomponents date-formatting

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

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

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

我知道它会与NSDateComponents有关,但我找不到任何帮助。

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分:1)

试试这个,您可以根据自己的选择更改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);
}