Home > database >  ZonedDateTime localized format
ZonedDateTime localized format

Time:07-21

I want to display ZonedDateTime in format like

11.10.2022 13:30 (GMT 2) / 11.10.2022 01:30 PM (GMT 2)

depending on device settings. So far I have done something similar using formatDateTime function from DateUtils class, but this function doesn't display

(GMT 2)

It takes time in milliseconds as a argument. How can I do this with ZonedDateTime?

CodePudding user response:

Use DateTimeFormatter helper from java.time.format to format ZonedDateTime, for example:

val time = ZonedDateTime.now()
val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm (O)")
formatter.format(time) // will return time in format 11.10.2022 13:30 (GMT 2)

See which symbols you can use to construct the pattern in the official docs.

To implement your particular case, you can also use DateTimeFormatterBuilder:

val time = ZonedDateTime.now()
val formatter = DateTimeFormatterBuilder()
    .appendPattern("dd.MM.yyyy ")
    .appendLocalized(null, FormatStyle.SHORT)
    .appendPattern(" (O)")
    .toFormatter()
formatter.format(time) // will return time depending on Locale

The last line of the code will return time in the desired format:

11.10.2022 13:30 (GMT 2) / 11.10.2022 01:30 PM (GMT 2)

Depending on device Locale:

Locale.FRANCE / Locale.US

  • Related