Two points that have more or less been covered in the comments, but which I thought deserved to go into an answer:
- A
LocalDateTime
hasn’t got, as in cannot have a format.
- 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