Search code examples
javastringdatesimpledateformatparseexception

SimpleDateFormat possible error in method parse


I receive a string that represent a date, I need convert this string to date, and validate that the string is a valid date.

I receive the string 33-12-2013 a the parse method return a date 01-01-2014, the code:

Date fechaVencimientoFormateada;
SimpleDateFormat formateador = new SimpleDateFormat( "dd-MM-yyyy" );
try
{
    fechaVencimientoFormateada = formateador.parse( "33-12-2013" );      
    System.out.println( formateador.format(fechaVencimientoFormateada) );
}
catch ( ParseException e )
{
    System.out.println("ERROR!");
}

the output: Thu Jan 02 00:00:00 COT 2014

and I expected a ParseException, any idea?

And other examples:

String date: 365-12-2013 output: Sun Nov 30 00:00:00 COT 2014

String date: 1-24-2013 output: Mon Dec 01 00:00:00 COT 2014

why ParseException is not throwing?


Solution

  • Make sure you setLenient(false) on the SimpleDateFormat. Otherwise it will parse lots of invalid dates without exception and you can't trust the output too much.