Objective c 列出过去的六个月
我正在寻找一种方法来获取从今天开始的过去六个月的列表 今天是5月,因此我希望获得以下产出:Objective c 列出过去的六个月,objective-c,cocoa,nsdatecomponents,date-formatting,Objective C,Cocoa,Nsdatecomponents,Date Formatting,我正在寻找一种方法来获取从今天开始的过去六个月的列表 今天是5月,因此我希望获得以下产出: May 2013, Apr 2013, Mar 2013, Feb 2013, Jan 2013, Dec 2012 我知道它将与NSDateComponents有关,但我找不到关于这一点的任何帮助。我建议与以下内容一起使用: [[NSDate date] mt_dateMonthsBefore:1]; [[NSDate date] mt_dateMonthsBefore:2]; [[NSDate da
May 2013,
Apr 2013,
Mar 2013,
Feb 2013,
Jan 2013,
Dec 2012
我知道它将与NSDateComponents
有关,但我找不到关于这一点的任何帮助。我建议与以下内容一起使用:
[[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];
尝试此操作,您可以根据自己的选择更改
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);
}
NSDate*今天=[[NSDate alloc]init];
NSCalendar*gregorian=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents*offsetComponents=[[NSDateComponents alloc]init];
对于(int i=0;我非常感谢!我实际上用类似的方法解决了这个问题,回来更新我的帖子,我已经有了答案。非常感谢!将格式化程序创建和设置移动到for
循环之外,可以极大地提高它的性能。格式化程序的创建是一个很大的过程性能开销,因此您应该尽可能重复使用