IOS时间格式区别
问题:使用NSDateFormatter 进行NSString和NSDate对象转换时,格式字符串中使用“hh”,在iOS设备 日期与时间设置项中24小时制设置项处于关闭的设置下,小时 大于12的NSString对象转换成NSDate对象时会返回nil。
- 时间格式的含义:
- yy表示Year, Y表示Week Year,计算方式不一样,通常使用【y】
- MM是为了和分钟的m区分,Month in year
- dd是Day in month,D是Day in year
- HH是24小时制Hour in day,hh是12小时制Hour in am/pm
- mm是分,Minute in hour
- ss是秒Second in minute,S是Millisecond
- aa是Am/pm marker
我们写如下一段代码进行测试:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSString *timeStr = @"2021-12-12 13:15:59";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd hh:mm:ss";
NSDate *currentDate = [dateFormatter dateFromString:timeStr];
NSLog(@"currenDate==========%@",currentDate);
}
- 当IOS设备 日期与时间设置项中24小时制设置项处于关闭的设置下,
- 使用
hh
去解析时间,可以看到如下打印结果:
- 使用
- 如果使用
hh
,但是小时没有超过12
,也是可以解析正常的,如下:
- 使用
HH
解析 是可以正常的解析的:
- 当IOS设备 日期与时间设置项中24小时制设置项处于开启状态下, 不管是
hh
还是HH
,不管小时有没有超过12
,都是可以正常的解析成功的