Search code examples
javajava-timedatetime-parsing

Parse nano seconds with less than 6 digits


I have the Timestamp 2017-07-25 16:19:59.89384

I want to parse it with:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
LocalDate time = LocalDateTime.parse(timeStamp, formatter);

But I get a DateTimeParseException because the nano seconds are only 5 digits. Is there a cleaner solution than padding 0's to the right?


Solution

  • If the input always has 5 digits in nanoseconds, you can use five S letters instead of six:

    String timeStamp = "2017-07-25 16:19:59.89384";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSS"); // five "S"
    LocalDateTime datetime = LocalDateTime.parse(timeStamp, formatter);
    

    Also note that LocalDateTime.parse returns a LocalDateTime (not a LocalDate like in your code).


    If you don't know how many digits will be in the input, you can use a java.time.format.DateTimeFormatterBuilder with a java.time.temporal.ChronoField and define the minimum and maximum number of digits:

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        // date / time
        .appendPattern("yyyy-MM-dd HH:mm:ss")
        // nanoseconds, with minimum 1 and maximum 9 digits and a decimal point
        .appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
        // create formatter
        .toFormatter();
    LocalDateTime datetime = LocalDateTime.parse(timeStamp, formatter);
    

    You just need to adjust the values 1 and 9 according to your needs.