Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 277
Divya Jain Avatar asked Dec 16 '22 14:12

Divya Jain


1 Answers

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
like image 90
Anoop Vaidya Avatar answered Dec 29 '22 00:12

Anoop Vaidya