ludo
ludo

Reputation: 1479

NSDateFormater from NSMutableArray value

I store some dates in my NSMutableArray, I want to retrieve them and change the format. For the moment I do this:


NSDate *myDate = [self.dates objectAtIndex:0];
NSLog(@"myDate:%@", myDate); // 2010-03-02
NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
[formatDate setDateFormat:@"MMMM d YYYY"];

NSString *newDate = [formatDate stringFromDate:myDate];
NSLog(@"newDate: %@", newDate); // NULL

the result for newDate is NULL, and I want it to be something like that: "March 3, 2010"

thanks,

Upvotes: 1

Views: 268

Answers (2)

user121301
user121301

Reputation:

Since your dates array contains strings, you have to convert the string to an NSDate and then you can re-convert the date to the format you want.

NSDateFormatter *strToDateFmt = [[NSDateFormatter alloc] init];
[strToDateFmt setDateFormat:@"yyyy-MM-dd"];
NSDate *myDate = [strToDateFmt dateFromString:[self.dates objectAtIndex:0]];
[strToDateFmt release];
NSLog(@"myDate:%@", myDate);

NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
[formatDate setDateFormat:@"MMMM d YYYY"];
NSString *newDate = [formatDate stringFromDate:myDate];
[formatDate release];
NSLog(@"newDate: %@", newDate);

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225042

That works for me, but I replaced the first line with:

NSDate *myDate = [NSDate date];

My output:

2010-03-02 19:29:08.045 app[11464:a0f] myDate:2010-03-02 19:29:08 -0800
2010-03-02 19:29:08.048 app[11464:a0f] newDate: March 2 2010

My best guess is that [self.dates objectAtIndex:0] isn't returning what you want it to.

Upvotes: 3

Related Questions