Search code examples
javadatedatetimeparsingdate-format

Unparseable date: "2018-08-02T14:24:40.040353"


I am trying to parse a DateTime from C# to Java. Here is what comes as string from the java call "2018-08-02T14:24:40.040353". When I try to parse it, I get the following error Unparseable date: "2018-08-02T14:24:40.040353"

Here is the method for parsing the date

public static String dateFormater(String dateFromJSON, String 
    expectedFormat, String oldFormat) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(oldFormat);
    Date date = null;
    String convertedDate = null;
    try {
        date = dateFormat.parse(dateFromJSON);
        SimpleDateFormat simpleDateFormat = new 
        SimpleDateFormat(expectedFormat);
        convertedDate = simpleDateFormat.format(date);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return convertedDate;
}

Solution

  • Your date look like a ISO_LOCAL_DATE_TIME, If you are using Java8 you can use java.time API and use the default format of LocalDateTime like this :

    String dateString = "2018-08-02T14:24:40.040353";
    LocalDateTime ldt = LocalDateTime.parse(dateString);
    

    ldt.toString():

    2018-08-02T14:24:40.040353