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

95 Views Asked by At

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

2

There are 2 best solutions below

2
ishaan On

use DateTimeFormatter

or

you can do this

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2024-03-01 09:20:46");
1
Basil Bourque On

As the Comments explain:

  • If you want strict parsing, without tolerating problematic inputs, specify strict parsing.
  • You are using terribly flawed date-time classes that are now legacy. Those classes were years ago supplanted by the modern java.time classes defined in JSR 310. Use only java.time classes.

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.