【问题标题】:why following code is not generate proper output base on input date [duplicate]为什么以下代码不能根据输入日期生成正确的输出[重复]
【发布时间】:2020-05-05 17:23:10
【问题描述】:
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
date1 = dateFormat.format(new Date(date));
System.out.println(date+" "+date1);

我的输入是date = 30-Dec-2019,预期的输出是2019-12-30

我得到的输出是2020-12-30

【问题讨论】:

  • 不要再使用旧的 simpledateformat 和 java.util.Date Api。使用新的 java.times.* API。并且是 yyyy 而不是 YYYY。
  • 如果您需要有关使用过时 API 的代码方面的帮助,请至少发布可编译的代码。
  • 已弃用的 Date(String) 构造函数不接受该格式的输入。
  • 我建议(1)不要使用SimpleDateFormatDate。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalDateDateTimeFormatter。 (2) 即使你坚持使用Date,也要远离那些被弃用的构造函数。它们已被弃用超过 23 年,因为它们跨时区工作不可靠。
  • 使用小的 yyyy 我解决了这个问题

标签: java date datetime simpledateformat date-formatting


【解决方案1】:

不要使用过时的日期/时间 API。使用现代日期/时间 API 执行此操作,如下所示:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {

    public static void main(String[] args) throws Exception {
        DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
        DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String strDate = "30-Dec-2019";
        LocalDate date = LocalDate.parse(strDate, inputFormat);
        System.out.println(outputFormat.format(date));
    }
}

输出:

2019-12-30

查看this,了解过时的日期/时间 API 的缺点和现代日期/时间 API 的优点。

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 2019-05-08
    相关资源
    最近更新 更多