[Solved] Format date by provided time zone in java [duplicate]


Use the modern Java date and time classes for everything that has got to do with dates or times.

    DateTimeFormatter usFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.US);
    System.out.println(date.format(usFormatter));
    DateTimeFormatter deFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.GERMANY);
    System.out.println(date.format(deFormatter));

This will print something like

6/27/17
27.06.17

It’s not exactly the formats you asked for, but it’s the formats Java thinks are appropriate for those two locales. I’d try them, and if the users complaint, build my own DateTimeFormatter from a pattern string (like MM/dd/uuuu, for example).

I used a LocalDate for the date in the code, but the same code should work with a LocalDateTime, OffsetDateTime or ZonedDateTime.

If you meant to deduce the locale from the time zone in a ZonedDateTime, I don’t think you can do that reliably. There are often many countries in a time zone, each country having its own locale and its own way of formatting dates. Germany, for example, shares its time zone with Norway, Sweden, Denmark, Poland, France, Switzerland, Austria and Italy, Spain, Serbia and many others.

And if you meant to deduce it from the time zone in an oldfashioned Date object, you certainly cannot simply because a Date does not hold a time zone in it.

5

solved Format date by provided time zone in java [duplicate]