gpt4 book ai didi

java - MMM 格式的 SimpleDateFormat 打印 "."

转载 作者:行者123 更新时间:2023-12-02 16:36:07 26 4
gpt4 key购买 nike

我正在尝试使用 SimpleDateFormat 将日期字符串从一种格式转换为另一种格式。转换有效,但有一个点“。”一个月后。

    String dateStr = "04/02/1987";
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
Date d = df1.parse(dateStr);
DateFormat df2 = new SimpleDateFormat("dd MMM yyyy");
System.out.println(df2.format(d));

输出是 1987 年 2 月 4 日 而不是 1987 年 2 月 4 日

最佳答案

您的 Locale.getDefault() 是什么?

字母数字日期部分的不同输出可能是由格式化程序使用的 Locale 引起的。在大多数情况下,如果您没有自己指定,系统默认的 Locale 将被使用。我不确定 SimpleDateFormat 是否会这样做,但看起来很有可能。

我知道 java.time.format.DateTimeFormatter 会这样做,请参阅以下使用 java.time 的示例,这是现代且推荐使用的 datetime API:

public static void main(String[] args) {
String dateStr = "04/02/1987";
LocalDate localDate = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd MMM yyyy",
Locale.ENGLISH)));
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd MMM yyyy",
Locale.FRENCH)));
}

输出:

04 Feb 1987
04 févr. 1987

关于月份名称的输出(当然)是不同的,但是使用 Locale.FRENCH 会在缩写的月份名称后显示一个点。您系统的默认 Locale 可能也是用点表示缩写的,但与数字部分的 Locale.ENGLISH 的输出格式相同月份的缩写。

关于java - MMM 格式的 SimpleDateFormat 打印 ".",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62710408/

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