java带时区时间格式,在Java中按提供的时区格式化日期

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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值