DateTimeFormatter格式化日期

时间:2025-04-01 08:29:32
public static void main(String[] args) { // 格式化年月日 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate localDate = LocalDate.now(); String formatLocalDate = dateTimeFormatter.format(localDate); System.out.println("格式化localDate:"+ formatLocalDate); String timeText = "15/12/2019"; // dd/MM/yyyy的文本解析成LocalDate LocalDate parseDate = LocalDate.parse(timeText, dateTimeFormatter); System.out.println("parseDate:"+ parseDate); // 格式化时分秒 DateTimeFormatter format1 = DateTimeFormatter.ofPattern("HH:mm:ss"); LocalTime localTime = LocalTime.now(); String formatLocalTime = format1.format(localTime); System.out.println("格式化localTime:"+ formatLocalTime); String timeText2 = "11:20:25"; // HH:mm:ss的文本解析成LocalTime LocalTime parseTime = LocalTime.parse(timeText2, format1); System.out.println("parseTime:"+ parseTime); // 格式化年月日时分秒 DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime nowDateTime = LocalDateTime.now(); String formatDateTime = format.format(nowDateTime); System.out.println("格式化dateTime:"+ formatDateTime); String timeText3 = "2019-12-15 11:20:25"; LocalDateTime parseDateTime = LocalDateTime.parse(timeText3, format); System.out.println("parseDateTime:" + parseDateTime); }