The parsing problem of SimpleDateFormat of Java

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Date date = sdf.parse("2018063");
System.out.println(sdf.format(date)); // =>202303

SimpleDateFormat does not throw an exception for a time string that does not match, but converts it to a different kind of time. How to make it throw an exception when it does not conform to the format?

Mar.29,2022

looks like it thinks this is canonical input, 63 = 5 * 12 + 3 .

maybe you can see if there is a stricter method of format specification


found the answer. The default is a loose policy. As long as you set this.sdf.setLenient (false);, you can enable strict policy


use joda-time

try{
            DateTime.parse("2018063", DateTimeFormat.forPattern("yyyyMM"));
        } catch(Exception e){
            e.printStackTrace();
        }
java.lang.IllegalArgumentException: Invalid format: "2018063" is malformed at "3"
Menu