How to disable zero padding mitigation in SimpleDateFormat

I use SimpleDateFormatwith a template "MM"and try to parse "0012".

Even with reduced failure, the formatter will successfully analyze this until December. I would like this exception, this is not a 2-digit month. Does anyone know how to achieve this?

the code

Code example:

SimpleDateFormat df = new SimpleDateFormat( "MM");
df.setLenient( false);
System.out.println( df.parse( "0012"));

Conclusion:

Tue Dec 01 00:00:00 CET 1970

+4
source share
3 answers

Just go and use the java.timemodern Java date and time API. DateTimeFormatter.ofPattern("uuuu-MM-dd")parses it 00like a month and then an object, because it does not follow a hyphen -(that is, before even checking that 00 is not a valid month number).

, java.time. SimpleDateFormat, , , .

: Oracle: , , java.time.

+1

, . , 2- ( , ) , :

try{

    if(str.length() > 2){

        int crash = (1/0);

    }

}catch (ArithmeticException e){

    System.out.println("You've introduced a month format larger than MM");

    //introduce the code you'll like to be executed when the Exception is 
    //fired.

}

, . . - , , .

0

, 0012 - , MMyy :

SimpleDateFormat df = new SimpleDateFormat("MMyy");
df.setLenient(false);
System.out.println(df.parse("0012"));

:

java.text.ParseException: Unparseable date: "0012"
-1

Source: https://habr.com/ru/post/1693199/


All Articles