Search code examples
javajava-timelocaldatetimedatetimeformatter

missing second(00) from LocalDateTime.parse


missing second (00) from LocalDateTime.parse

LocalTime time = LocalTime.NOON;
DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("HH:mm:ss");
String value ="20200810" + time.format(formatTime);
LocalDateTime localDateTime = LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyyMMddHH:mm:ss"));

LOGS

=========value========== 2020081012:00:00
===localDateTime===2020-08-10T**12:00**

I tried to change LocalTime.NOON to LocalTime.of(12,0,0) too but still same result.


Solution

  • Write the following line into log:

    localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
    

    The above line returns a string as per DateTimeFormatter.ISO_LOCAL_DATE_TIME.

    You can also specify a custom pattern as per your requirement e.g.

    localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
    

    or

    localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHH:mm:ss"))
    

    If you print localDateTime directly, it will print the string returned by toString method of LocalDateTime.

    Note that since the second part in the time, 12:00:00 is 00, the default toString implementation of LocalDateTime ignores the second part.

    For your reference, given below is the toString() implementation of LocalDateTime:

    @Override
    public String toString() {
        return date.toString() + 'T' + time.toString();
    }
    

    and given below the toString() implementation of LocalTime:

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder(18);
        int hourValue = hour;
        int minuteValue = minute;
        int secondValue = second;
        int nanoValue = nano;
        buf.append(hourValue < 10 ? "0" : "").append(hourValue)
            .append(minuteValue < 10 ? ":0" : ":").append(minuteValue);
        if (secondValue > 0 || nanoValue > 0) {
            buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
            if (nanoValue > 0) {
                buf.append('.');
                if (nanoValue % 1000_000 == 0) {
                    buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
                } else if (nanoValue % 1000 == 0) {
                    buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
                } else {
                    buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
                }
            }
        }
        return buf.toString();
    }
    

    As you can see, the second and nano parts are included only when their values are greater than 0.