Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change date from one format to another using NSDateFormatter

Tags:

ios

ios5

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);
like image 303
newdev1 Avatar asked Dec 20 '22 15:12

newdev1


1 Answers

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
like image 200
Rich Avatar answered Apr 06 '23 00:04

Rich