Parsing timestamp as LocalDateTime

后端 未结 2 1287
野趣味
野趣味 2020-12-12 07:09

I want to parse a timestamp in the form of yyyy-MM-dd\'T\'HH:mm:ss as LocalDateTime. When doing so, it strips the seconds if they are 00

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 07:09

    You should expect a difference in output between

    LocalDateTime dateLDT = LocalDateTime.parse(dateFormatted, f);
    System.out.println(dateLDT);
    

    And

    System.out.println(dateLDT.format(f)) //or f.format(dateLDT)
    

    System.out.println(dateLDT); prints the value of dateLDT.toString(), which is not expected to produce the same output as your pattern.

    When you look at LocalDateTime.toString(), you'll see that it delegates the time part to LocalTime.toString(), which prints seconds conditionally:

    public String toString() {
        ...
        if (secondValue > 0 || nanoValue > 0) {
            buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
            ...
            }
        }
        return buf.toString();
    }
    

    It simply omits the seconds field if its value is 0.

    What you need to do in this case is always use a DateTimeFormatter to format your date if you have to be certain about the output/input format.

提交回复
热议问题