传过来的参数时间格式是:
2020-9-28 11:22:33
我们需要将其变成:
2020-09-28 11:22:33
使用 DateTimeFormatter
public static String getTransTime(String timeStr) { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-M-dd HH:mm:ss"); LocalDateTime date = LocalDateTime.parse(timeStr, df); DateTimeFormatter f2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String transTime = f2.format(date); return transTime; } 工具类调试 public static void main(String[] args) throws ParseException { String timeStr = "2020-9-28 11:22:33"; String transTime = getTransTime(timeStr); System.out.println(transTime); }
测试结果:
再试试传已经正常带有0的:
测试结果(没影响):