challengeAccepted
challengeAccepted

Reputation: 7600

Parse date string to a specific format in Java

I have a date '2021-06-19 14:57:23.0' which I need to change it to LocalDateTime type. When I parse, it throws Text could not be parsed at index 10.

String date = "2021-06-19 14:57:23.0";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime date = LocalDateTime.parse(date, formatter);

What am I missing here? I have a string in a format which I am converting to a different format by specififying.

Upvotes: 0

Views: 467

Answers (2)

Anonymous
Anonymous

Reputation: 86276

Two points that have more or less been covered in the comments, but which I thought deserved to go into an answer:

  1. A LocalDateTime hasn’t got, as in cannot have a format.
  2. To change from one string format to another you generally need two formatters, one for parsing the format that you have got and one for formatting into the desired format.

So you will need to decide whether you need a LocalDateTime or you need the format that you specified since you cannot have both in the same object. But: in your particular case you can almost. Stealing the code from the answer by Ctrl_see:

    String dateString = "2021-06-19 14:57:23.0";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.S"); 
    LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
    
    System.out.println("Parsed date and time: " + dateTime);

Output is:

Parsed date and time: 2021-06-19T14:57:23

Only the three decimals that you asked for were not output. The format that we get from LocalDateTime.toString() (implicitly called when we concatenate the LocalDateTime to a string) is ISO 8601, and according to the ISO 8601 standard the decimals are optional when they are 0. So please check if the above isn’t fine for your purpose.

If you do need the decimals, as I said, we will need a second formatter to format back into a string having the desired format:

    DateTimeFormatter targetFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS");
    String formattedDateTimeString = dateTime.format(targetFormatter);
    System.out.println(formattedDateTimeString);

2021-06-19T14:57:23.000

Links

Upvotes: 1

Kleysley
Kleysley

Reputation: 573

You have the wrong pattern for your date. The right pattern for you would be:

String date = "2021-06-19 14:57:23.0"; // declaring the date variable
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); // declaring the pattern. Here was your error. 
LocalDateTime date = LocalDateTime.parse(date, formatter);

Upvotes: 2

Related Questions