在Java中按提供的时区格式化日期 [英] Format date by provided time zone in java

查看:1019
本文介绍了在Java中按提供的时区格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为提供的时区用Java格式化日期时间.例如. mm/dd/yyyy(美国)和dd/mm/yyyy(美国).我有时区,我可以获取zoneId,有人可以帮助我.非常感谢.

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.

推荐答案

将现代Java日期和时间类用于与日期或时间有关的所有事情.

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));

这将打印出类似的内容

6/27/17
27.06.17

这不是您要求的格式,而是Java认为适合这两种语言环境的格式.我会尝试一下,如果用户抱怨,请使用模式字符串(例如MM/dd/uuuu)构建我自己的DateTimeFormatter.

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).

我在代码中的date中使用了LocalDate,但相同的代码应与LocalDateTimeOffsetDateTimeZonedDateTime一起使用.

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

如果您想从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.

如果要从老式的Date对象的时区推断出它,肯定不能仅仅因为Date在其中不包含时区.

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.

这篇关于在Java中按提供的时区格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆