javadatetimepaddingdate-formattingzero-pad

Pad DateTimeFormatter with traling zeros


I'm creating an application where the user picks a date and time in a calendar which then should be shown in a text field as 26 digits, padding the date with trailing zeroes.

So the date should be displayed in the following format:

yyyyMMddHHmmssSSS000000000

So after millisecond (SSS) I want to fill out the string with 9 zeros. The problem is that this does not seem to be possible without adding a whitespace between the pattern letters and the zero constants.

The funny thing is that if I do DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS000000000") I get a DateTimeParseException, but the String is actually formatted as desired in the textfield. Problem is that when surrounding the instantiation of DateTimeFormatter with a try-catch block, Eclipse tells me Unreachable catch block for DateTimeParseException. This exception is never thrown from the try statement body because the exception is thrown in some dependency class to my textfield. Moreover, it seems bad practice to catch an error that will be thrown every time the code is executed.

DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS 000000000") does compile. But I really need it to be a String without any whitespaces.

Is this possible? I'm currently using java.time.format.DateTimeFormatter, but if there's some class out the there extending it, I guess using it would be okay as well. Although I would prefer avoiding adding additional dependencies.


Solution

  • Use DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS'000000000'")