NSDateFormatter not working properly?

2019-03-06 05:38发布

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???

2条回答
贪生不怕死
2楼-- · 2019-03-06 06:22

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

查看更多
小情绪 Triste *
3楼-- · 2019-03-06 06:26

try doing:

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

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

查看更多
登录 后发表回答