问题
I need to format date time in java for provided time zone. E.g. mm/dd/yyyy for US and dd/mm/yyyy for DE. I have time zone and i can get zoneId, can someone help me. Many thanks.
回答1:
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.
回答2:
Hope this will help you,
import java.util.*;
import java.text.*;
public class DateDemo {
   public static void main(String args[]) {
        Date date1 = new Date();
        System.out.println(date1);
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        Date date2 = new Date();
        System.out.println(date2);
        TimeZone.setDefault(TimeZone.getTimeZone("EST"));
        Date date3 = new Date();
        System.out.println(date3);
   }
}
Output:
Tue Jun 06 14:02:51 IST 2017
Tue Jun 06 08:32:51 UTC 2017
Tue Jun 06 03:32:51 EST 2017
    来源:https://stackoverflow.com/questions/44384625/format-date-by-provided-time-zone-in-java