7

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?

Rana Depto
  • 721
  • 3
  • 11
  • 31
  • 2
    If it's in that exact format: `new StringBuilder().append(start, 6, 10).append('-').append(start, 3, 5).append('-').append(start, 0, 2).toString()`. – Andy Turner Dec 08 '17 at 08:45
  • 2
    Give an explicit format pattern for parsing: `LocalDate.parse(startDateString, DateTimeFormatter.ofPattern("dd-MM-uuuu"))`. – Ole V.V. Dec 08 '17 at 09:38
  • @AndyTurner Thanks! Here it is good formated:`new StringBuilder().append(start, 8, 10).append('-').append(start, 5, 8).append(start, 0, 4).toString();` – Perkone Feb 11 '22 at 14:54

2 Answers2

20

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));
Joe Rakhimov
  • 4,713
  • 9
  • 51
  • 109
  • 2
    Please don’t teach the young ones to use the long outdated and notoriously trouble some `SimpleDateFormat` class. Especially not when he is already using `LocalDate` from `java.time`, the modern Java date and time API. This is so much nicer to work with. – Ole V.V. Dec 08 '17 at 09:35
  • 1
    @OleV.V. thank you for pointing out. I did not know about DateTimeFormatter) See updated answer. – Joe Rakhimov Dec 08 '17 at 12:24
  • This won't work when date is 7/4/1986 for example. – Vivek Apr 27 '23 at 09:55
4

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);
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously trouble some `SimpleDateFormat` class. Especially not when he is already using `LocalDate` from `java.time`, the modern Java date and time API. This is so much nicer to work with. – Ole V.V. Dec 08 '17 at 09:35