AM/PM issue in NSDateFormatter

筅森魡賤 提交于 2019-12-23 16:20:02

问题


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


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/14498420/am-pm-issue-in-nsdateformatter

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