Why my NSDateFormatter returns null?

2019-01-15 21:00发布

Why my NSDateFormatter returns null? Here is my code:

  NSString *dateString = @"21-12-2012 11:05:15";
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm:ss"];
  NSDate *dateFromString = [[NSDate alloc] init];
  dateFromString = [dateFormatter dateFromString:dateString];

  [dateFormatter setDateFormat:@"dd/MM/yyyy"];
  NSString *strDate = [dateFormatter stringFromDate:dateFromString];

My strDate returns

21/12/2012

but when:

NSString *dateString = @"13-12-2012 13:17:58";

My strDate returns null

This is very weird, anyone has experienced the same?

2条回答
爷、活的狠高调
2楼-- · 2019-01-15 21:05

Use HH instead of hh.

hh usually is 12 hour time while HH is usually 24 hour time.

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

A good official reference for this, as linked by Apple themselves, is here. Another good table is here, as mentioned by Zaph.

查看更多
地球回转人心会变
3楼-- · 2019-01-15 21:13

You should use

[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
查看更多
登录 后发表回答