Search code examples
javatimelocalizationjava-timezoneddatetime

ZonedDateTime localization


I need to output ZonedDateTime according to the locale I get later. Is there any way I can convert the ZonedDateTime value to the required format?

ZonedDateTime creationDate=ZonedDateTime.now();
//convert creationDate depending on the existing locale

Solution

  • ZonedDateTime doesn't have a format. The concept of a ZonedDateTime is format-less.

    Formatters are their own objects (instances of DateTimeFormatter). They are configurable (for example, you can change their locale, and all the locale-specific rendering they do, such as long-form month names, will then change), and you can ask them to format a provided zoneddatetime.

    Thus, make your zoneddatetime object whenever you want, store it whereever you want. If, 3 days later, you need to format it according to some locale you just now got, great. Do that then:

    ZonedDateTime zdt = ZonedDateTime.now();
    // days pass
    
    DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).localizedBy(Locale.FRENCH);
    
    System.out.println(dtf.format(zdt));