SimpleDateFormat("MMM d, yyyy") 返回平日月日 00:00:00 EDT 年

问题描述 投票:0回答:1

我有一个字符串列表 [2019 年 4 月 1 日、2020 年 8 月 1 日、2018 年 2 月 20 日],我需要以相同的模式将其转换为日期格式。当我使用 SimpleDateFormat("MMM d, yyyy") 模式执行此操作时,我得到 Thu Aug 01 00:00:00 EDT 2019 格式。尝试使用 Joda DateTimeFormatter 并得到相同的结果。 有谁可以帮忙解决吗?

simpledateformat
1个回答
0
投票

java.time

java.util
日期时间 API 及其格式化 API
SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到现代日期时间 API

另外,下面引用来自Joda-Time主页的通知:

请注意,从 Java SE 8 开始,用户被要求迁移到 java.time (JSR-310) - JDK 的核心部分,它将取代该项目。

使用现代日期时间 API

java.time
的解决方案:

public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("Apr 1, 2019", "Aug 1, 2020", "Feb 20, 2018");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d, uuuu", Locale.ENGLISH);
        list.forEach(s -> {
            LocalDate date = LocalDate.parse(s, dtf);
            System.out.printf("Default format: %s, Custom format: %s%n", date, date.format(dtf));
        });
    }
}

输出:

Default format: 2019-04-01, Custom format: Apr 1, 2019
Default format: 2020-08-01, Custom format: Aug 1, 2020
Default format: 2018-02-20, Custom format: Feb 20, 2018

在线演示

注意:在这里,您可以使用

y
代替
u
,但我更喜欢
u
而不是
y
。另外,切勿将
DateTimeFormatter
用于没有区域设置的自定义格式

Trail:日期时间了解有关现代日期时间 API 的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.