Search code examples
javalocalizationformattingdate-formattinglocaldate

How to format LocalDate to the standard format for the user's location?


How can I format a LocalDate based on the standard of the user's location. I want people in the U.S. to see "6/28/2018" while people in Europe to see "28/6/2018" and people in China to see "2018/6/28".

Do I need to use DateTimeFormatter formatter = ... or would I need to use something else?

I will also need to convert a string to a LocalDate based on the standards of the user's location.


Solution

  • One way to do is to use DateTimeFormatter.ofLocalizedDate() factory method which returns a locale specific date format for the ISO chronology.

    DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
    LocalDate now = LocalDate.now(); // 2018-10-05
    String txt = fmt.format(now); // Friday, 5 October 2018
    LocalDate d = LocalDate.parse(txt, fmt); // 2018-10-05