LocalDateTime.format(DateTimeFormatter) 和 DateTimeFormatter.format(TemporalAccessor) 有什么区别?

What is the difference between LocalDateTime.format(DateTimeFormatter) and DateTimeFormatter.format(TemporalAccessor)?

在 Java 8 DateTime API 中,有 2 种格式化日期的方法,乍一看似乎做同样的事情:

DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm").format(LocalDateTime.now());
LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"));

这两个 return 表示运行时日期和时间的字符串。

这两个之间有显着差异吗?

不,它们是等效的 - 甚至 记录 它们是等效的,至少对于默认实现是这样。 ChronoLocalDateTime.format 包括这个:

The default implementation must behave as follows:

return formatter.format(this);

有时一种形式有用,有时另一种形式有用 - 这可能取决于您在更长的表达式中链接在一起的内容。