Home > Net >  How to parse a yyyy-MM-dd HH:mm:ss to Date?
How to parse a yyyy-MM-dd HH:mm:ss to Date?

Time:09-02

I'm trying to parse a date with the format "" to Date.

DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = sdf.parse(dateStr);
String = sdf.format(date);

An example of the dateStr is "2020-04-14 16:34:40.0117372".

I get an error when trying to parse the string, but I don't know why.

The error I'm getting is the following:

java.text.ParseException: Unparseable date: "2020-04-14 16:34:40.0117372"

Why can't I parse this date? How can I do it?

CodePudding user response:

You are using "dd/MM/yyyy" for date format, but you should be using "yyyy-MM-dd" (inverse order, and dashes instead of slashes)

Also I suggest you use modern java.time packages and do something like this:

String str = "2020-04-14 16:34:40.0117372";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Edit: Having 7 digits for milliseconds is strange. Usually you want 3 digits because 1000 milliseconds is a second. You likely have nanoseconds, which should be dealt with by this method.

  • Related