Home > Net >  How to format date/time/zone to pattern with offset from UTC in Java?
How to format date/time/zone to pattern with offset from UTC in Java?

Time:12-24

I have timestamp. For example:

OffsetDateTime timestamp = OffsetDateTime.parse("2022-12-23T12:00:00.000 02:00");

How can I format it via DateTimeFormatter? I can't find format pattern, which I need:

"23.12.2022 at 12:00 (UTC 2)"

And can't create new, because when I use:

DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd.MM.uuuu 'at' HH:mm ('UTC'X)"); // getting UTC 02, but we need UTC 2

then I get UTC 02, but we need UTC 2.

Additional question: can we get word UTC via pattern?

CodePudding user response:

You can use the DateTimeFormatterBuilder.appendOffset method, which supports various formats for offsets. Choose one that do not have 0 paddings on the hour.

DateTimeFormatter formatter = 
    new DateTimeFormatterBuilder()
         .appendPattern("dd.MM.uuuu 'at' HH:mm ('UTC'")
         .appendOffset(" H:mm:ss", " 0")
         .appendLiteral(")")
         .toFormatter();

If you want "UTC" to be part of a pattern symbol, that would be a localised offset (O), which means this depends on the locale.

Only as a proof of concept (:D), I have found that the French locale calls offsets "UTC±x".

DateTimeFormatter formatter = 
    DateTimeFormatter.ofPattern("dd.MM.uuuu 'at' HH:mm (O)")
        .withLocale(Locale.FRENCH);

Though in other locales, you'd get "GMT±x" instead.

  • Related