Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

date - 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...