简体   繁体   中英

NSDateFormatter how can I format this date?

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM