Home > Software engineering >  Change date format Java getting Unparseable date Error
Change date format Java getting Unparseable date Error

Time:12-16

I have a date in the following format:

lastUpdatedDate = "12/14/2021 09:15:17"; 

I used the following code/format to convert date into yyyy-MM-dd hh:mm:ss format:

SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);

But it gives me below error:

java.text.ParseException: Unparseable date: "12/14/2021 09:15:17"

output should be: 2021-12-14 09:15:17

How can I achieve this?

CodePudding user response:

Change the format to

SimpleDateFormat dt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);

System.out.println(lastUpdatedDateFormatted);

And it should be able to parse the date then.

CodePudding user response:

As you are wanting to display or output the date in yyyy-MM-dd HH:mm:ss format, you should parse the date first then format the date to desired format.

try {
   String lastUpdatedDate = "12/14/2021 09:15:17";
   Date lastDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(lastUpdatedDate);
   System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lastDate));
} catch (ParseException e) {
   e.printStackTrace();
}

CodePudding user response:

Your formatting pattern fails to match your input string.

And you are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.

java.time

The modern solution uses the java.time classes.

Your input lacks an indicator of time zone or offset from UTC, so parse as a LocalDateTime object.

LocalDateTime ldt = 
    LocalDateTime
    .parse(
        "12/14/2021 09:15:17" ,
        DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss" ) ;
    ) ;

Your desired output is nearly compliant with the ISO 8601 standard format used by default in java.time, except for that SPACE in the middle rather than T.

String output = ldt.toString().replace( "T" , " " ) ;
  • Related