sivasubramanian B
sivasubramanian B

Reputation: 53

Java 8 DateTimeFormatterBuilder appendValue zeroPadding Not working as expected

I am trying to format the milliseconds to 3 digit on serialize to ISOString from offsetDate Time

Value Expected Actual
2020-06-16T05:47:40.1-06:00 2020-06-16T11:47:40.001Z 2020-06-16T11:47:40.100Z
2020-06-16T05:47:40.12-06:00 020-06-16T11:47:40.012Z 020-06-16T11:47:40.120Z

When I used

private static final DateTimeFormatter outFormatter = new DateTimeFormatterBuilder()
        .parseLenient()
        .append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
        .appendLiteral('.')
        .appendValue(ChronoField.MILLI_OF_SECOND,3)
        .appendZoneId()
        .toFormatter()
        .withZone(ZoneId.from(ZoneOffset.UTC));

The documentation says padding will be on Left. But I am getting padding on right.

Any suggestion on how to achieve with date Formatter?

Upvotes: 2

Views: 324

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79435

.1 in 2020-06-16T05:47:40.1-06:00 represents the fraction-of-second i.e. .1 second and thus, can be also written as .100 second. In terms of millisecond, it will be .1 * 1000 = 100 milliseconds.

Apart from this, you can simplify your code greatly by using OffsetDateTime#withOffsetSameInstant, as shown below:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(parseOdtStrAndConvertWithOffsetSameInstant("2020-06-16T05:47:40.1-06:00"));
        System.out.println(parseOdtStrAndConvertWithOffsetSameInstant("2020-06-16T05:47:40.12-06:00"));
    }

    static String parseOdtStrAndConvertWithOffsetSameInstant(String text) {
        OffsetDateTime odt = OffsetDateTime.parse(text).withOffsetSameInstant(ZoneOffset.UTC);
        return odt.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX"));
    }
}

Output:

2020-06-16T11:47:40.100Z
2020-06-16T11:47:40.120Z

Upvotes: 1

Related Questions