Change date from one format to another using NSDateFormatter

匿名 (未验证) 提交于 2019-12-03 08:50:26

问题:

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

回答1:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!