NSDateFormatter not working properly?

心不动则不痛 提交于 2020-03-16 11:18:20

问题


My code ,

-(NSString *)trimDateStringInRequiredFormat:(NSString *)dateInString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:dateInString];
    [dateFormatter setDateFormat:@"hh:mm aaa"];
    NSString *dateDisplay = [dateFormatter stringFromDate:date];
    return dateDisplay;
}

The above worked properly when my date is 2012-06-06 12:00:00 and I got appropriate output like 12:00 AM. But when I send my date like 2012-06-06 15:00:00 it doesn't return me appropriate output, instead, it returns me null output. When I'm trying to trace this function the 2012-06-06 15:00:00 date on NSDate *date = [dateFormatter dateFromString:dateInString]; this line not properly converted. Why did this happen? where am I wrong in this code???


回答1:


try doing:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

With hh you have the 12h format, with HH you use 24h format




回答2:


This is because for 24 Hr format you need to use HH instead of hh



来源:https://stackoverflow.com/questions/9989476/nsdateformatter-not-working-properly

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