Java 如何将 LocalDateTime 格式化为字符串
// 获取当前的日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
// 使用内部定义的ISO_DATE_TIME格式
static DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
// 自定义格式
//DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化 LocalDateTime
String formattedDateTime = currentDateTime.format(formatter);
// 查看结果
System.out.println("Formatted LocalDateTime : " + formattedDateTime);		
//Output:
//Formatted LocalDateTime : 2018-07-14T17:45:55.9483536
  • parse()format()方法可用于所有与日期/时间相关的对象(LocalDateTimeLocalDate或者 ZonedDateTime)。
  • DateTimeFormatter是不可变的和线程安全的,因此推荐的方法是尽可能将其存储在静态常量中。
日期:2020-09-17 00:09:19 来源:oir作者:oir