1、java.util.Date类
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(date);
System.out.println("未格式化:" + date);
System.out.println("格式化后:" + dateString);
未格式化:Thu Aug 26 14:27:26 CST 2021
格式化后:2021-08-26 14:27:26
2、java.time.LocalDateTime类
LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
String localDateTimeString = localDateTime.format(dateTimeFormatter);
System.out.println("未格式化:" + localDateTime);
System.out.println("格式化后:" + localDateTimeString);
未格式化:2021-08-26T14:27:26.787
格式化后:2021/08/26 14:27:26