将NSDate的NSArray转换为格式化日期数组作为字符串

时间:2012-11-02 18:51:10

标签: objective-c ios for-loop nsdate

我在NSArray格式的NSArray中有一系列非连续日期。我需要在数组中使用相同的日期集,但在NSString中格式化为dd / MM。我想我需要循环读取原始数组中的每个日期,将其转换为字符串并根据需要对其进行格式化,但我无法弄清楚如何逐步完成原始数组。

NSError *error2;
NSArray *swim750mArray = [context executeFetchRequest:request2 error:&error2];
if (swim750mArray == nil) {
    NSLog(@"The fetch request2 returned an array == nil");
} else {
    NSLog(@"The fetch request2 returned an array...");
    NSLog(@"%@", swim750mArray);

NSArray *datesAsDates = [swim750mArray valueForKey:@"date"];
NSMutableArray* arrayOfDatesAsStrings = [NSMutableArray arrayWithCapacity:count];

    //SomeCode - Convert the Array of NSDates to a new Array of dates as NSStrings...

      for (int i=0; i<index; i++) {
           //get the date next NSDate from the array as: NSDate *dateAsDate...
           NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
           [dateFormat setDateFormat:@"dd/MM"];


         NSString *dateAsStr = [dateFormat stringFromDate:dateAsDate];

         [arrayOfDatesAsStrings addObject:dateAsStr];
        }

这个答案接近我的需要,除了它没有从现有数组中读入:How to use NSDate formatter with an array of dates?

请帮忙!非常感谢...

2 个答案:

答案 0 :(得分:4)

如何使用fast enumeration

for (NSDate* dateAsDate in datesAsDates) {
     //get the date next NSDate from the array as: NSDate *dateAsDate...
     NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
     [dateFormat setDateFormat:@"dd/MM"];

     NSString *dateAsStr = [dateFormat stringFromDate:dateAsDate];

     [arrayOfDatesAsStrings addObject:dateAsStr];
}

答案 1 :(得分:1)

jere命名为快速枚举。它也可以用block-based enumeration来完成。你也是should create a formatter once and re-use it

NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
[dateFormater setDateFormat:@"dd/MM"];

NSMutableArray *datesAsStrings = [NSMutableArray array];
[datesAsDates enumerateObjectsUsingBlock:^(NSDate *date, NSUInteger idx, BOOL *stop){
     NSString *dateString = [dateFormater stringFromDate:date];
     [datesAsStrings addObject:dateString] 
}];

如果您想坚持使用C风格,请执行

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM"];
for (int i=0; i< [datesAsDates count]; i++) {       
    NSString *dateAsStr = [dateFormat stringFromDate:[dateAsDate objectAtIndex:i]]; 
    [arrayOfDatesAsStrings addObject:dateAsStr];
}

但由于突变保护,首选枚举。