2013-05-16 21 views
1

我正在尋找一種方法來獲取從今天起的最近六個月的列表。列出前六個月

今天是五月,所以我要尋找的輸出:

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

我知道它會是與NSDateComponents,但我不能找到這個任何幫助。

回答

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); 
} 
+0

完美的感謝!我真的用類似的方法解決了它,回到這裏更新我的帖子,我已經有了答案。非常感激! –

+0

通過將'formatter'的創建和設置移動到'for'循環之外,可以顯着改善這種性能。格式化程序的創建是一個很大的性能開銷,因此您應該嘗試在可能的情況下重新使用 – jr19

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];