Divya Jain Divya Jain - 16 days ago 5
iOS Question

AM/PM issue in NSDateFormatter

I write below code to convert one date format into another dateformat.
But AM string works and PM did not work .
Please help-

dateTime=@"2013-01-24 18:30 PM";
//dateTime=@"2013-01-24 06:30 AM";
NSDateFormatter *dtFormatter=[[NSDateFormatter alloc]init];
[dtFormatter setDateFormat:@"yyyy-MM-dd hh:mm a"];
NSDate *AptDate=[dtFormatter dateFromString:dateTime];
[dtFormatter setDateFormat:@"MMM dd,yyyy hh:mm a"];
NSString *strDate=[dtFormatter stringFromDate:AptDate];


Here I get AptDate variable as null if i use PM format

Answer

You need to use HH in place of hh, as your time is in 24 hour format:

[dtFormatter setDateFormat:@"yyyy-MM-dd HH:mm a"];

Your full code will go as:

*dateTime=@"2013-01-24 18:30 PM";
//dateTime=@"2013-01-24 06:30 AM";
NSDateFormatter *dtFormatter=[[NSDateFormatter alloc]init];
[dtFormatter setDateFormat:@"yyyy-MM-dd HH:mm a"];
NSDate *AptDate=[dtFormatter dateFromString:dateTime];
[dtFormatter setDateFormat:@"MMM dd,yyyy hh:mm a"];
NSString *strDate=[dtFormatter stringFromDate:AptDate];

NSLog(@"===> %@",AptDate);
NSLog(@"===> %@",strDate);

Output:

===> 2013-01-24 07:00:00 +0000
===> Jan 24,2013 12:30 PM
Comments