How to parse date-time with two or three milliseconds digits in java?

brain storm :

Here is my method to parse String into LocalDateTime.

    public static String formatDate(final String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS");
        LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
        return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
    }

but this only works for input String like 2017-11-21 18:11:14.05 but fails for 2017-11-21 18:11:14.057 with DateTimeParseException.

How can I define a formatter that works for both .SS and .SSS?

Basil Bourque :

tl;dr

No need to define a formatter at all.

LocalDateTime.parse(
    "2017-11-21 18:11:14.05".replace( " " , "T" )
)

ISO 8601

The Answer by Sleiman Jneidi is especially clever and high-tech, but there is a simpler way.

Adjust your input string to comply with ISO 8601 format, the format used by default in the java.time classes. So no need to specify a formatting pattern at all. The default formatter can handle any number of decimal digits between zero (whole seconds) and nine (nanoseconds) for the fractional second.

Your input is nearly compliant. Just replace the SPACE in the middle with aT.

String input = "2017-11-21 18:11:14.05".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );

ldt.toString(): 2017-11-21T18:11:14.050

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441502&siteId=1