Jonatan Stenbacka
Jonatan Stenbacka

Reputation: 1864

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.

Upvotes: 1

Views: 2575

Answers (2)

Ortomala Lokni
Ortomala Lokni

Reputation: 62635

Use the a DateTimeFormatterBuilder with the appendPattern method

public DateTimeFormatterBuilder appendPattern(String pattern)

Appends the elements defined by the specified pattern to the builder.

All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The characters '#', '{' and '}' are reserved for future use. The characters '[' and ']' indicate optional patterns.

You can use it like this:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
public class TimeFormatteTest {
    public static void main(String[] args){
        DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
        dtfb.append(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        dtfb.appendPattern("000000000");
        DateTimeFormatter dtf = dtfb.toFormatter();
        System.out.println(dtf.format(LocalDateTime.now()));
    }
}

The output will be in the form:

20151104003532968000000000

Upvotes: 1

Ken Geis
Ken Geis

Reputation: 922

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

Upvotes: 1

Related Questions