javadatetimesimpledateformat

SimpleDateFormat gives a wrong date when input a wrong format date string


code is

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = format.parse("2024-03-01 09:20:46");

the date's value is Sun Dec 03 00:01:09 CST 2023 without any Exception.

I read some comment in jdk, it might show that '-' will treat to minus , is it real? And how to understand the read think in the method SimpleDateFormat.parse


Solution

  • tl;dr

    LocalDateTime.parse( "2024-03-01 09:20:46".replace( " " , "T" ) )
    

    Details

    As the Comments explain:

    ResolverStyle.STRICT

    In java.time, specify parsing strictness on a DateTimeFormatter class by calling withResolverStyle, and passing a ResolverStyle enum object: LENIENT, SMART , STRICT.

    ISO 8601

    By the way, your example input string nearly complies with the ISO 8601 standard format used by default in java.time for parsing/generating text. Merely replace the SPACE character in the middle with a T.

    java.time.LocalDateTime

    Then you can parse as a LocalDateTime. No need to specify a formatting pattern.

    String input = "2024-03-01 09:20:46".replace( " " , "T" ) ;
    LocalDateTime ldt = LocalDateTime.parse( input ) ;
    

    Be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. A LocalDateTime object is inherently ambiguous in that it represents only a date with time-of-day while lacking the context of a time zone or offset-from-UTC.