在Java 8中格式化LocalDateTime时,默认DateTimeFormatter返回空字符串

Mic*_*das 1 java datetime datetime-format java-8 java-time

以下代码返回一个空字符串:

LocalDateTime.parse("2018-01-01T00:00:00.00")
    .format(new DateTimeFormatterBuilder().toFormatter())
Run Code Online (Sandbox Code Playgroud)

我期望一个例外或以某种默认方式格式化的日期.

我是否在Java中发现了一个错误,或者这是否符合规范?我在Javadoc中找不到有关此行为的任何信息.

gre*_*449 5

DateTimeFormatterBuilder用于构建格式,它从空开始.您必须调用其各种方法,例如appendPattern添加所需的格式.

DateTimeFormatter有一些标准格式你可以直接使用.这些用于DateTimeFormatterBuilder构建格式.例如:

public static final DateTimeFormatter ISO_LOCAL_DATE;
static {
    ISO_LOCAL_DATE = new DateTimeFormatterBuilder()
            .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
            .appendLiteral('-')
            .appendValue(MONTH_OF_YEAR, 2)
            .appendLiteral('-')
            .appendValue(DAY_OF_MONTH, 2)
            .toFormatter(ResolverStyle.STRICT, IsoChronology.INSTANCE);
}
Run Code Online (Sandbox Code Playgroud)


Ser*_*tin 5

您的代码相当于:

LocalDateTime.parse("2018-01-01T00:00:00.00").format(DateTimeFormatter.ofPattern(""))
Run Code Online (Sandbox Code Playgroud)

在所有情况下都会产生一个空字符串.