Roland
Roland

Reputation: 18415

How to disable zero-padding leniency in SimpleDateFormat

I'm using SimpleDateFormat with pattern "MM" and try to parse "0012".

Even with leniency disabled the formatter will successfully parse this to december. I'd like it to throw an exception, this is no 2-digit-month. Does anyone know how to achieve that?

Code

Example code:

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

Output:

Tue Dec 01 00:00:00 CET 1970

Upvotes: 3

Views: 1217

Answers (3)

Anonymous
Anonymous

Reputation: 86333

Just move on and use java.time, the modern Java date and time API. DateTimeFormatter.ofPattern("uuuu-MM-dd") will parse 00 as the month and then object because it isn’t followed by a hyphen, - (that is, before even checking to see that 00 isn’t a valid month number).

I think you should want to use java.time anyway. The SimpleDateFormat class you’re using is not only outdated, it is also notoriously troublesome.

Link: Oracle Tutorial: Date Time explaining how to use java.time.

Upvotes: 1

daffd
daffd

Reputation: 1

Assuming that 0012 is month and year with 2 digits each, you can use MMyy as pattern:

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

This will throw the following exception,

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

Upvotes: 0

Alex Cuadrón
Alex Cuadrón

Reputation: 688

This might not be the best solution for this problem, but here it goes. I suggest checking if the value introduced by the user is bigger than 2 digits (I supposed the input is an String) inside of an exception handler and creating an exception if it does:

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.

}

I understand this is not the best way to solve this issue. However, it works. If someone has any better idea just tell me and I'll edit my answer.

Upvotes: 0

Related Questions