I have this datestring:
2011-11-01T13:00:00.000
and I don't seem to get that one parsed no matter
if I try SimpleDateformat
or the DateTimeformatter
My last try is this one:
LocalDateTime datetime = LocalDateTime.parse(
deliverydate,
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.S"));
But that gives me an error on index 21. Do I simply need to substring that datestring since I actually only care about the date and not the time?
You've specified one digit of subsecond precision - but you've got three. Use SSS
and it's fine:
String text = "2011-11-01T13:00:00.000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime datetime = LocalDateTime.parse(text, formatter);
Also note how much more readable the code is when you separate out "creating the formatter" from "parsing the value".
Unlike SimpleDateFormat
, DateTimeFormatter
is immutable and thread-safe, so if you need to use this more than once I'd suggest extracting it to a static final field:
private static final DateTimeFormatter DELIVERY_DATE_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ROOT);
See more on this question at Stackoverflow