AM/PM issue in NSDateFormatter

2019-06-24 05:09发布

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

3条回答
forever°为你锁心
2楼-- · 2019-06-24 05:44

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
查看更多
贪生不怕死
3楼-- · 2019-06-24 05:47

For those who are looking for Swift 3 version of Accepted answer.

let date1            = Date()
let formatter        = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
print(formatter.string(from: date1))

let dateTime            = "2013-01-24 18:30 PM"
let dateFormater        = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd HH:mm a"
let AptDate             = dateFormater.date(from: dateTime)
dateFormater.dateFormat = "MMM dd,yyyy hh:mm a"
let strDate             = dateFormater.string(from: AptDate!)

print("===> \(AptDate!)")
print("===> \(strDate)")
查看更多
Deceive 欺骗
4楼-- · 2019-06-24 06:02
UILabel *dateLabel = (UILabel *)[cell viewWithTag:400];
NSString *oldDate = [exercise objectForKey:@"date"];
//make formatter
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //24 hour format
NSDate *tempDate=[formatter dateFromString:oldDate];
NSLog(@"temp date %@", tempDate);
[formatter setDateFormat:@"hh:mm a"];
NSString *newDate=[formatter stringFromDate:tempDate];
NSLog(@"new date %@", newDate);
//make label text
[dateLabel setText:newDate];

For anyone looking from mySQL with a DATETIME stamp to a regular hh:mm a format showing AM/PM correctly this worked for me.

查看更多
登录 后发表回答