利用DateTimeFormatter 来格式化时间时,报DateTimeParseException异常

时间:2025-03-17 20:51:26

利用DateTimeFormatter 来格式化时间时,报 : Text ‘2018-3-15 00:00:00’ could not be parsed at index 5 异常

Exception in thread "main" java.time.format.DateTimeParseException: Text '2018-3-15 00:00:00' could not be parsed at index 5
    at java.time.format.DateTimeFormatter.parseResolved0(:1949)
    at java.time.format.(:1851)
    at java.time.(:492)
    at (:179)
    at (:167)

原因:当month小于10时,’MM’ 解析失败,前面加上0则解析成功.

 public static void main(String[] args) {
        getInstants((),15);
    }

    private static  Instant[] getInstants(LocalDate localDate, int day) {
        int month = ().getValue();
        int year = ();
//        String monthStr = month < 10 ? ("0" + month) : month + "";
        String monthStr = (month);
        String dateStringStart = ("%d-%s-%d 00:00:00", year, monthStr, day);
        String dateStringEnd = ("%d-%s-%d 23:59:59", year, monthStr, day);
        DateTimeFormatter dateTimeFormatter = ("yyyy-MM-dd HH:mm:ss");

        LocalDateTime start = (dateStringStart, dateTimeFormatter);
        LocalDateTime end = (dateStringEnd, dateTimeFormatter);
        //解析日期
        Instant[] instant = new Instant[2];
        instant[0] = ((8));
        instant[1] = ((8));
        return instant;
    }