代码 public class Test { public static void main(String[] args) { /** * String转为时间日期格式 */ //String转换为localDate LocalDate localDate = LocalDate.parse("2022-04-18"); DateTimeFormatter patter = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); System.out.println(localDate); System.out.println(LocalDate.parse("2022-04-18").format(patter)); //String转换为LocalTime LocalTime localTime = LocalTime.parse("14:45:45"); //String转换为LocalDateTime DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");//12小时格式时间 DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//24小时格式时间 LocalDate localDate1 = LocalDate.parse("2022-04-18 14:54:56",formatter1); System.out.println(localTime); System.out.println(localDate1); /** * 时间转为String */ //LocalDate转为String LocalDate localDate2 = LocalDate.now(); String formate1 = localDate2.format(DateTimeFormatter.BASIC_ISO_DATE); System.out.println(localDate2); System.out.println(formate1); //LocalTime转为String LocalTime localTime1 = LocalTime.now(); String format3 = localTime1.format(DateTimeFormatter.ISO_TIME); DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm:ss"); String format4 = localTime1.format(formatter2); System.out.println(format3); System.out.println(format4); //LocalDateTime转为String LocalDateTime localDateTime = LocalDateTime.now(); DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String format5 = localDateTime.format(formatter3); System.out.println(format5); } }
输出结果:
2022-04-18
2022年04月18日
14:45:45
2022-04-18
2022-04-18
20220418
15:25:19.869
03:25:19
2022-04-18 03:25:19