Change date from one format to another using NSDateFormatter

How to convert NSDateFormatted string Apr 18, 2014 10:34:19 AMto 2014-04-18T17:34:19? I tried below, but it returns a pointer nil NSDate. Can someone here please help me. Thank.

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);
+4
source share
1 answer

You need to use 2 date formats, one to parse the other to display:

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
+11
source

Source: https://habr.com/ru/post/1536999/


All Articles