1. 字符串转LocalDate
1 public static LocalDate parseDateString(String dateString, String pattern){ 2 try{ 3 DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); 4 return LocalDate.parse(dateString, formatter); 5 }catch (DateTimeParseException ex){ 6 ex.printStackTrace(); 7 return null; 8 } 9 }
2. LocalDate转字符串
1 public static String formatDate(LocalDate date, String pattern){ 2 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern); 3 return date.format(dateFormatter); 4 }
3. 字符串转LocalDateTime
1 public static LocalDateTime parseTimeString(String timeString, String pattern){ 2 try{ 3 DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); 4 return LocalDateTime.parse(timeString, formatter); 5 }catch (DateTimeParseException ex){ 6 ex.printStackTrace(); 7 return null; 8 } 9 }
4. LocalDateTime转字符串
1 public static String formatTime(LocalDateTime time, String pattern){ 2 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern); 3 return time.format(dateFormatter); 4 }
测试代码:
1 public static void main(String[] args) { 2 LocalDate date = parseDateString("2022年12月8日", "y年M月d日"); 3 System.out.println(formatDate(date, "MM/dd/yyyy")); 4 5 LocalDateTime time = parseTimeString("2022年12月8日 8:22:5","y年M月d日 H:m:s"); 6 System.out.println(formatTime(time, "yyyy-MM-dd HH时mm分ss秒")); 7 }
输出结果是:
12/08/2022
2022-12-08 08时22分05秒