DateTimeFormatter desiredFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
String truncatedDateTimeString = "2017-06-05T19:27";
LocalDateTime dateTime = LocalDateTime.parse(truncatedDateTimeString);
String fixedDateTimeString = dateTime.format(desiredFormatter);
System.out.println(fixedDateTimeString);
This prints
2017-06-05T19:27:00.000000
If also the minutes and hours are missing, we need some more trickery, though. Look into DateTimeFormatterBuilder
and its parseDefaulting
method. Use square brackets []
in the format pattern string to surround the parts that may be missing. I am not sure what your string will look like if the hours have been truncated — will the T
be missing too?
On the other hand the above also works if the string was 2017-06-05T19:27:10.917360
, and in this case just prints the same string back.
Also I am not sure which problem you are really trying to solve. Trailing zeroes are redundant, so what is the problem in them being truncated?
Edit: The following method fleshes out what I said about DateTimeFormatterBuilder
, its parseDefaulting
method and square brackets in the format pattern string:
public static String addTrailingZerosToTimestamp(String timeStamp) {
DateTimeFormatter truncatedFormatter = new DateTimeFormatterBuilder()
.appendPattern("uuuu-MM-dd['T'HH[:mm[:ss[.SSSSSS]]]]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
.toFormatter();
DateTimeFormatter desiredFormatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(timeStamp, truncatedFormatter);
return dateTime.format(desiredFormatter);
}
It works with 2017-06-05
, 2017-06-05T19
, 2017-06-05T19:27
, 2017-06-05T19:27:10
and 2017-06-05T19:27:10.917360
, but not with 2017-06-05T19:27:10.917
.