Java 8 LocalDateTime is parsing invalid date

前端 未结 5 626
南旧
南旧 2020-11-27 07:04

I wanted to validate date in client side so I wrote the following code. But instead of getting an exception I am getting a proper date object for 31st of February date strin

5条回答
  •  长情又很酷
    2020-11-27 07:50

    try {
        SimpleDateFormat df = new java.text.SimpleDateFormat("HH:mm:ss MM/dd/yyyy");
        df.setLenient(false);
        System.out.println(df.parse("11:30:59 02/29/2015"));
    } catch (java.text.ParseException e) {
      System.out.println(e);
    }
    

    I found one solution to recognize date as a valid date with DateFormat.setLenient(boolean). If you try to parse any invalid date it will throws parse exception.

    Edit:

    Java 8, but this will raise exception if a month is not between 1 and 12, if a day is more than 32. Exactly not working. But for month its working.

    try {
    TemporalAccessor ta = DateTimeFormatter.ofPattern("HH:mm:ss MM/dd/yyyy").parse("11:30:59 02/32/2015");
    } catch (Exception e) {
    System.out.println(e);
    }
    

    Output:

    java.time.format.DateTimeParseException: Text '11:30:59 02/32/2015' could not be
     parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 32
    

提交回复
热议问题