gpt4 book ai didi

具有短日期模式的 java 本地化日期

转载 作者:行者123 更新时间:2023-11-30 03:04:33 25 4
gpt4 key购买 nike

对于下面的代码:

public class DateFormatTest {

@Test
public void shouldTestDateFormat() {

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
System.out.println(df.format(new Date()));

df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
System.out.println(df.format(new Date()));
}
}

输出是:

2/1/16
01.02.16

如何获得下面的输出而不是之前的输出:

2/1/2016
01.02.2016

注意:短日期的区域设置为:英语(美国)、MM/dd/yyyy。

当我更改区域设置而不是短日期模式时,我需要上面的输出。我不需要关心世界上所有的模式。代码模拟语言环境的变化:

    localize(Locale.getDefault());
localize(Locale.GERMANY);

private void localize(Locale locale) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
System.out.println(df.format(new Date()));
}

最佳答案

以下代码不能保证有效,但不幸的是,这是我所知道的唯一方法,并且它适用于 Oracle 的 Java 7 和 8 实现。如果它不起作用,它将打印 2 位数的年份。

private static void printLocalizedDate(Locale locale) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
if (df instanceof SimpleDateFormat)
df = new SimpleDateFormat(
((SimpleDateFormat) df).toPattern().replace("yy", "yyyy")
);
System.out.println(df.format(new Date()));
}

printLocalizedDate(Locale.getDefault());
printLocalizedDate(Locale.GERMANY);

关于具有短日期模式的 java 本地化日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35128114/

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