jorstern
jorstern

Reputation: 33

Formatting ZonedDateTime according to locale

I have a ZonedDateTime object that I'd like to format according to a given Locale. I.e. in the US, I'd like the format to be "M-dd-yy", but in the UK it should be "dd-M-yy".

What is the best way to do this given a specified locale?

Upvotes: 3

Views: 1627

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 339402

The java.time classes can automatically localize the generation of text.

Locale locale = Locale.CANADA_FRENCH ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale ) ;

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Edmonton" ) ) ;
String output = zdt.format( f ) ;

See this code run live at IdeOne.com.

jeudi 10 juin 2021 à 18 h 16 min 51 s heure avancée des Rocheuses

If you want the date-only as seen in British style, extract a LocalDate, and localize with Locale.UK.

myZdt
.toLocalDate()
.format(
    DateTimeFormatter
    .ofLocalizedDate(
        FormatStyle.SHORT
    )
    .withLocale( 
        Locale.UK
    )
)

11/06/2021

But both Java 16 and the Wikipedia page Date and time notation in the United Kingdom disagree with your statement that:

in the UK it should be "dd-M-yy"

Instead, Wikipedia claims UK style is DD/MM/YY, while Java 16 outputs a four-digit year. In my experience, a two-digit year causes nothing but confusion; I highly recommend always using 4-digit years.

If you want to force a pattern, use DateTimeFormatter.ofPattern.

Upvotes: 2

Related Questions