【问题标题】:List the previous six months [duplicate]列出前六个月 [重复]
【发布时间】: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


    【解决方案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);
    }
    

    【讨论】:

    • 非常感谢!我实际上用类似的路线解决了它,回到这里更新我的帖子,我已经有了答案。非常感谢!
    • formatter 创建和设置移到for 循环之外可以显着提高性能。格式化程序的创建是一个很大的性能开销,所以你应该尽可能地重复使用
    【解决方案2】:

    我建议将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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多