如何在不使用模式的情况下在 DateTimeFormatterBuilder 中指定区域偏移量?

How do I specify a zone offset in a DateTimeFormatterBuilder without using a pattern?

我正在尝试将以下时间戳解析为 ZonedDateTime:

Sun Jan 20 16:08:59 +0000 2019

我喜欢尽可能避免使用字符串中定义的模式,因为我经常忘记字符代表什么 ("huh, is 'M' month of year, or minute of hour...?")

在下面的示例中,我如何去掉代表区域偏移的模式 "xxxx"?我试过 appendOffsetId 但它使用不同的模式,所以解析失败。

有没有更好的方法?

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
    .appendLiteral(' ')
    .appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT)
    .appendLiteral(' ')
    .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NEVER)
    .appendLiteral(' ')
    .appendValue(ChronoField.HOUR_OF_DAY, 2)
    .appendLiteral(':')
    .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
    .appendLiteral(':')
    .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
    .appendLiteral(' ')
    .appendPattern("xxxx")   // How do I change this?
    .appendLiteral(' ')
    .appendValue(ChronoField.YEAR, 4)
    .toFormatter();

System.out.println(
    ZonedDateTime.parse("Sun Jan 20 16:08:59 +0000 2019", formatter)
);

您可以使用 appendOffset 而不是 appendOffsetId。第一个参数是一个模式,但不是 DateTimeFormatter 模式;实际上它被限制为 22 个可能的字符串值:

.appendOffset("+HHMM", "????")