How to use NSDate formatter with an array of dates?

☆樱花仙子☆ 提交于 2019-12-22 01:07:40

问题


I'm trying to generate an array of 30 days from the current date and put them into an array formatted correctly. I currently have a working generater to get 30 days from the current date and put it into an array but I don't know how to use NSDate formatter for an array. I know how to use the formatter for a single item but how can I format all the dates in my array? The format that I would like is (Month Day). Here's my code:

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);

Any help would be appreciated, Thanks.


回答1:


use like this,

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);



回答2:


i suggest you to give the NSDate formatter to your date first and then give those objects to the NSMutableArray and whenever you fetch the object from an array you get the required format.

Hope you get my point...Good Luck!



来源:https://stackoverflow.com/questions/5012381/how-to-use-nsdate-formatter-with-an-array-of-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!