1

I have a requirement where if ISO date time does not specify zone offset, I should assume Europe/Bratislava's current offset.

Basically "2020-03-26T22:47:32.497" -> "2020-03-26T22:47:32.497+01:00"

Tldr; do parse time zone id if there is one, but default to a specific one if none is present

What I have now

private val isoDateTimeParser = DateTimeFormatterBuilder()
    .append(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
    .parseDefaulting(ChronoField...?)
    .toFormatter()

Obviously it doesnt work. Is it even possible? Should I just have 2 formatters (one with tz, one without) and try one after another?

urSus
  • 12,492
  • 12
  • 69
  • 89

1 Answers1

1

Add an "override zone" to the formatter with withZone

private val isoDateTimeParser = DateTimeFormatterBuilder()
    .append(DateTimeFormatter.ISO_DATE_TIME)
    .toFormatter()
    .withZone(/*whatever*/)

From the docs

If a zone has been parsed directly from the text, perhaps because DateTimeFormatterBuilder.appendZoneId() was used, then this override zone has no effect


By the way, there is very rarely any reason for a formatter to be an instance variable. It should be static. Given that it's immutable, and therefore a constant, it should be upper case as well.

private static final ISO_DATE_TIME_PARSER = ...
Michael
  • 41,989
  • 11
  • 82
  • 128