[雷]LocalDateTime使用过程中的一些坑----12小时进制的处理

时间:2025-03-17 21:03:33

项目场景:

香港项目


问题描述:

因为需求要求为12小时进制进行展示时间在文档的末端,DateTimeFormatter解析字符创LocalDateTime转换字符创时报错,
报错异常为:
: Text ‘2016-10-25 12:00:00 上午’ could not be parsed, unparsed text found at index 19


原因分析:

 String dateTimeStr= "2016-10-25 04:00:00 上午";
 DateTimeFormatter formatter02 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a");
 LocalDateTime localDateTime=LocalDateTime.parse(dateTimeStr,formatter02);
 System.out.println(localDateTime);
 String format = localDateTime.format(formatter02);
 System.out.println(format);
2016-10-25T04:00
2016-10-25 04:00:00 上午

解决方案:

如果格式是hh即12小时制,必须加上a也就是上午还是下午