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

问题: I'm trying to parse the following timestamp into a ZonedDateTime: Sun Jan 20 16:08:59 +0000 2019 I like to avoid using patterns defined in strings where I can because...

问题:

I'm trying to parse the following timestamp into a ZonedDateTime:

Sun Jan 20 16:08:59 +0000 2019

I like to avoid using patterns defined in strings where I can because I often forget what the characters stand for ("huh, is 'M' month of year, or minute of hour...?")

In the following example, how can I get rid of the pattern "xxxx", which represents a zone offset? I tried appendOffsetId but it uses a different pattern, so parsing fails.

Is there a better way?

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)
);

回答1:

You can use appendOffset rather than appendOffsetId. The first argument is a pattern, but not a DateTimeFormatter pattern; in fact it is limited to 22 possible String values:

.appendOffset("+HHMM", "????")
  • 发表于 2019-01-20 23:32
  • 阅读 ( 176 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除