Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 LocalDateTime - How to keep .000 milliseconds in String conversion

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.

like image 914
daniel9x Avatar asked Dec 31 '17 15:12

daniel9x


1 Answers

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));
like image 129
Ward Avatar answered Oct 16 '22 08:10

Ward