在 Java 中将日期格式 dd-MM-yyyy 更改为 yyyy-MM-dd

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47710475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:46:14  来源:igfitidea点击:

Change date format dd-MM-yyyy to yyyy-MM-dd in Java

javadatedatetime

提问by Rana Depto

I was trying to convert date string 08-12-2017 to 2017-12-08(LocalDate). Here is what I tried-

我试图将日期字符串 08-12-2017 转换为 2017-12-08(LocalDate)。这是我尝试过的-

    String startDateString = "08-12-2017";
    LocalDate date = LocalDate.parse(startDateString);
    System.out.println(date);

Also tried using formatter, but getting same result, an DateTimeParseException. How can I get an output like 2017-12-08, without getting an exception?

还尝试使用格式化程序,但得到相同的结果,DateTimeParseException。如何获得类似 2017-12-08 的输出,而不会出现异常?

回答by Joe Rakhimov

Try this (see update below)

试试这个(见下面的更新)

try {
    String startDateString = "08-12-2017";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf2.format(sdf.parse(startDateString)));
} catch (ParseException e) {
    e.printStackTrace();
}

Update - Java 8

更新 - Java 8

    String startDateString = "08-12-2017";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    System.out.println(LocalDate.parse(startDateString, formatter).format(formatter2));

回答by Hafsa Elif ?z?iftci

First you have to parse the string representation of your date-time into a Date object.

首先,您必须将日期时间的字符串表示形式解析为 Date 对象。

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date)formatter.parse("2011-11-29 12:34:25");

Then you format the Date object back into a String in your preferred format.

然后,您将 Date 对象格式化回您首选格式的 String。

DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String mydate = dateFormat.format(date);