【发布时间】:2013-05-11 07:04:44
【问题描述】:
我正在寻找一种方法来获取从今天起过去六个月的列表。
今天是五月,所以我会寻找以下输出:
May 2013,
Apr 2013,
Mar 2013,
Feb 2013,
Jan 2013,
Dec 2012
我知道这与NSDateComponents 有关,但我在这方面找不到任何帮助。
【问题讨论】:
标签: objective-c cocoa nsdatecomponents date-formatting
我正在寻找一种方法来获取从今天起过去六个月的列表。
今天是五月,所以我会寻找以下输出:
May 2013,
Apr 2013,
Mar 2013,
Feb 2013,
Jan 2013,
Dec 2012
我知道这与NSDateComponents 有关,但我在这方面找不到任何帮助。
【问题讨论】:
标签: objective-c cocoa nsdatecomponents date-formatting
试试这个,你可以根据自己的选择更改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);
}
【讨论】:
formatter 创建和设置移到for 循环之外可以显着提高性能。格式化程序的创建是一个很大的性能开销,所以你应该尽可能地重复使用
我建议将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];
【讨论】: