3
votes

I am attempting to format an NSString which looks like:

@"2012-07-19T02:58:33Z"

to an NSDate with the following format:

@"MMMM dd, yyyy HH:mm a"

The NSDateFormatter always returns nil and I think it is because it cannot convert the NSString in it's current format to the desired one. Here is my code:

 NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
        NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [formatter setLocale:enUSLocale];
        NSDate *date = [formatter dateFromString:dateString];

Do I need to store the date in a differant format? Can I make this conversion possible with the current NSString?

Thanks!

3

3 Answers

1
votes

Your dateFormatter doesn't match your dateString... Try this

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:enUSLocale];
NSDate *date = [formatter dateFromString:dateString];

[formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
dateString=[formatter stringFromDate:date];

now dateString contains "July 19, 2012 02:58 AM"

Hope this helps

1
votes

Try it.

NSString *myDateString=@"2012-07-19T02:58:33Z";//@"2009-07-06T17:42:12";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
 NSDate *myDate = [[NSDate alloc] init];
 myDate = [dateFormatter dateFromString:myDateString];
 NSLog(@"MyDate is: %@", myDate);
0
votes

Your problem has already been answered.

Store your string in a NSDate with the format of the original string:

NSString *originalDateString = @"2012-07-19T02:58:33Z";
NSDateFormatter *originalFormatter = [[NSDateFormatter alloc]init];
 [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:enUSLocale];
NSDate *originalDate = [formatter dateFromString:originalDateString];

NSDateFormatter *newFormatter = [formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
NSString *newDateString = [formatter stringFromDate:originalDate];