gpt4 book ai didi

java - 根据区域设置格式化 ZonedDateTime

转载 作者:行者123 更新时间:2023-12-05 04:48:44 27 4
gpt4 key购买 nike

我有一个 ZonedDateTime 对象,我想根据给定的区域设置对其进行格式化。 IE。在美国,我希望格式为“M-dd-yy”,但在英国则应为“dd-M-yy”。

在给定的语言环境下执行此操作的最佳方法是什么?

最佳答案

java.time 类可以 automatically localize文本的生成。

Locale locale = Locale.CANADA_FRENCH ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale ) ;

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Edmonton" ) ) ;
String output = zdt.format( f ) ;

查看此 code run live at IdeOne.com .

jeudi 10 juin 2021 à 18 h 16 min 51 s heure avancée des Rocheuses

如果您想要英国风格的纯日期,请提取 LocalDate,并使用 Locale.UK 进行本地化。

myZdt
.toLocalDate()
.format(
DateTimeFormatter
.ofLocalizedDate(
FormatStyle.SHORT
)
.withLocale(
Locale.UK
)
)

11/06/2021

但是 Java 16 和维基百科页面 Date and time notation in the United Kingdom不同意你的说法:

in the UK it should be "dd-M-yy"

相反,维基百科声称英国风格是 DD/MM/YY,而 Java 16 输出四位数年份。根据我的经验,两位数的年份只会造成困惑;我强烈建议始终使用 4 位数年份。

如果你想强制一个模式,使用DateTimeFormatter.ofPattern .

关于java - 根据区域设置格式化 ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67929633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com