【问题标题】:How to use NSDate formatter with an array of dates?如何将 NSDate 格式化程序与日期数组一起使用?
【发布时间】:2011-02-16 03:55:35
【问题描述】:

我正在尝试从当前日期生成一个包含 30 天的数组,并将它们放入格式正确的数组中。我目前有一个工作生成器可以从当前日期获取 30 天并将其放入一个数组中,但我不知道如何使用 NSDate 格式化程序作为数组。我知道如何将格式化程序用于单个项目,但如何格式化数组中的所有日期?我想要的格式是(月日)。这是我的代码:

NSMutableArray* dates = [[NSMutableArray alloc] init];
    int numberOfDays=30;
    NSDate *startDate=[NSDate date];
    NSDate *tempDate=[startDate copy];
    for (int i=0;i<numberOfDays;i++) {
        NSLog(@"%@",tempDate.description);
        tempDate=[tempDate dateByAddingTimeInterval:(60*60*24)];
        [dates addObject:tempDate.description];
    }

    NSLog(@"%@",dates);

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: iphone objective-c nsmutablearray nsarray nsdate


    【解决方案1】:

    我建议您先将NSDate formatter 提供给您的日期,然后将这些对象提供给NSMutableArray,每当您从数组中获取对象时,您都会获得所需的格式。

    希望你明白我的意思...祝你好运!

    【讨论】:

    • 这是一个很好的方法,我尝试实现它并通过这个概念给出答案。
    【解决方案2】:

    这样使用,

    NSMutableArray* dates = [[NSMutableArray alloc] init];
        int numberOfDays=30;
        NSDate *startDate=[NSDate date];
        NSDate *tempDate=[startDate copy];
        for (int i=0;i<numberOfDays;i++) {
            NSLog(@"%@",tempDate.description);
            tempDate=[tempDate dateByAddingTimeInterval:(60*60*24)];
         NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"MM/dd"];
        NSString *dateString = [dateFormat stringFromDate:tempDate];
        tempDate=[dateFormat dateFromString:dateString];
        [dateFormat release];
    
            [dates addObject:tempDate.description];
        }
    
        NSLog(@"%@",dates);
    

    【讨论】:

    • 日期对象总是使用这种格式,如果你想要任何自定义逻辑,那么你需要在 NSDateComponents 中转换它。你使用的任何格式都为日期对象提供相同的格式,但如果你在字符串中更改它,那么它只需提供您想要的。
    猜你喜欢
    • 1970-01-01
    • 2016-09-15
    • 2014-06-26
    • 2017-01-08
    • 2011-06-08
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多