Pregunta

How can I convert NSDateFormatted string Apr 18, 2014 10:34:19 AM to 2014-04-18T17:34:19? I have tried the below but it returns a nil NSDate pointer. Can anyone here please help me out. Thanks.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter  setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];
NSDate *date = [dateFormatter dateFromString:@"Apr 18, 2014 10:34:19 AM"];  // Error nil
NSLog(@"date: %@", date);
¿Fue útil?

Solución

You need to use 2 date formatters, one for parsing the other for displaying:

NSDateFormatter *parsingFormatter = [NSDateFormatter new];
[parsingFormatter setDateFormat:@"MMM dd, yyyy hh:mm:ss a"];
NSDate *date = [parsingFormatter dateFromString:@"Apr 18, 2014 10:34:19 AM"];
NSLog(@"date: %@", date);

NSDateFormatter *displayingFormatter = [NSDateFormatter new];
[displayingFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];
NSString *display = [displayingFormatter stringFromDate:date];
NSLog(@"display: %@", display); // 2014-04-18T17:34:19
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top