There are a couple of options. I would go for this one:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
String dateTimeString = "2018-04-18 15:27:10.77";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime);
Output:
2018-04-18T15:27:10.770
DateTimeFormatter.ISO_LOCAL_TIME
optionally accepts a decimal point and one to nine digits. I prefer using the builder to combine the predefined formatters rather than building my own from scratch.
There’s a shorter one that some prefer. Personally I find it a bit hacky:
dateTimeString = dateTimeString.replace(' ', 'T');
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
Output is the same. We’re exploiting two facts: (1) The one-arg LocalDateTime.parse
parses ISO 8601 format. (2) Your input string is very close to being in ISO 8601 format, it only lacks the T
that denotes the place where the time part begins.
You don’t need the third option, but for the sake of completeness I would like to mention: If building a formatter from scratch and needing a variable number of decimals, use DateTimeFormatterBuilder
(the class I used in the first snippet) and its appendFraction
method. It gives you control over the minimum and maximum number of decimals.