Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 列出过去的六个月_Objective C_Cocoa_Nsdatecomponents_Date Formatting - Fatal编程技术网

Objective c 列出过去的六个月

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

我正在寻找一种方法来获取从今天开始的过去六个月的列表

今天是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 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
循环之外,可以极大地提高它的性能。格式化程序的创建是一个很大的过程性能开销,因此您应该尽可能重复使用