Format datetime in java based on locale

60 views Asked by At

I want the date and time to be formatted based on the criteria(below objects) for each datetime component. And the separators between them should be taken based on locale. Is there way to achieve this in java

   { year: numeric, month: long, day: two-digit, weekday: short }   
   { year: numeric, month: twoDigit, day: twoDigit }
   For example consider second object and locale Locale.US and Locale.FRANCE.
   For Locale.US date should be 26/03/2024
   For Locale.France date should be 26.03.2024

I know I can use DateTimeFormatter.ofLocalizedDate(), which gives me the choice of four format styles for each locale, from short to full. I am after the greater flexibility of specifying for each field whether it should be numeric or textual and how long, the same that I can when specifying a format pattern string, but still with the right delimiters for the locale.

1

There are 1 answers

4
Basil Bourque On

To represent a date, use LocalDate class.

LocalDate localDate = LocalDate.of( 2024 , Month.MARCH , 26 ) ;

To generate text, use a DateTimeFormatter object.

To specify a particular format, define a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd/MM/uuuu" ) ;
String output = localDate.format( f ) ;

To automatically localize while generating text, use DateTimeFormatter.ofLocalizedDate. Specify a FormatStyle and a Locale.

For more complicated matters, use the DateTimeFormatterBuilder class to generate a DateTimeFormatter object.

Your Question is a bit too vague to say more. To learn more, search Stack Overflow as these topics have been addressed many times already.