I have a timestamp that I receive via a String
in the following format:
2016-10-17T12:42:04.000
I am converting it to a LocalDateTime
to add some days to it (then back to a String
) via the following line:
String _120daysLater = LocalDateTime.parse("2016-10-17T12:42:04.000",
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")).minusDays(120).toString());
However, I noticed that the response it gives back drops the .000
milliseconds.
I'm not sure the cleanest way to ensure that the exact pattern is preserved. For now I'm just adding a single millisecond, and there's probably a way to incorporate the old SimpleDateFormat
into it, but I was hoping there's an even better way.
LocalDateTime::toString omits parts if zero:
The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.
Use LocalDateTime::format instead of relying on toString()
.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime _120daysLater = LocalDateTime.parse("2016-10-17T12:42:04.000", formatter).minusDays(120);
// This just uses default formatting logic in toString. Don't rely on it if you want a specific format.
System.out.println(_120daysLater.toString());
// Use a format to use an explicitly defined output format
System.out.println(_120daysLater.format(formatter));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With