如何仅用分钟格式化 LocalDateTime(截断秒)?

How to format LocalDateTime with minutes only (truncate seconds)?

我有 LocalDateTime 个值,想使用 ISO_LOCAL_DATE_TIME 常量仅打印 分钟

两个测试用例都失败了:

Expected :2020-10-10T15:16
Actual   :2020-10-10T15:16:00

但是为什么呢?

assertEquals("2020-10-10T15:16", LocalDateTime.parse("2020-10-10T15:16:17")
                .truncatedTo(ChronoUnit.MINUTES)
                .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

assertEquals("2020-10-10T15:16", DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(
        LocalDateTime.parse("2020-10-10T15:16:17").truncatedTo(ChronoUnit.MINUTES)));

除此之外:使用第一种或第二种方法格式化 LocalDateTime 值的区别在哪里?

使用自定义格式化程序,当日期时间被截断为分钟时,ISO_LOCAL_DATE_TIME 将始终使用 00 作为秒数,因为该日期格式指定应包括秒数(而 0 是日期时间中秒字段的值)。

这应该有效

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
assertEquals("2020-10-10T15:16", LocalDateTime.parse("2020-10-10T15:16:17")
         //.truncatedTo(ChronoUnit.MINUTES) <-- not needed with that format
           .format(formatter));

您的用例不需要格式化程序

如果秒和纳秒字段为零,LocalDateTime#toString 默认情况下会忽略它们。

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

LocalDateTime#truncatedTo(ChronoUnit.MINUTES) 将秒和纳秒字段设置为零。

Truncation returns a copy of the original date-time with fields smaller than the specified unit set to zero. For example, truncating with the minutes unit will set the second-of-minute and nano-of-second field to zero.

因此,您的用例不需要格式化程序。

演示:

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        System.out.println(LocalDateTime.parse("2020-10-10T15:16:17").truncatedTo(ChronoUnit.MINUTES));
    }
}

输出:

2020-10-10T15:16