Change date format dd-MM-yyyy to yyyy-MM-dd in Java [duplicate]

喜夏-厌秋 提交于 2020-06-08 13:47:51

问题


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

    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?


回答1:


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

    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));



回答2:


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

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.

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


来源:https://stackoverflow.com/questions/47710475/change-date-format-dd-mm-yyyy-to-yyyy-mm-dd-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!