Incorrect date parsing using SimpleDateFormat, Java

AndrewVP picture AndrewVP · May 15, 2012 · Viewed 7.3k times · Source

I need to parse a date from input string using date pattern "yyyy-MM-dd", and if date will come in any other format, throw an error.

This is my piece of code where I parse the date:

private void validateDate() throws MyException {
  Date parsedDate;
  String DATE_FORMAT = "yyyy-MM-dd";
  try{
    parsedDate = new SimpleDateFormat(DATE_FORMAT).parse(getMyDate());
    System.out.println(parsedDate);
  } catch (ParseException e) {
    throw new MyException(“Error occurred while processing date:” + getMyDate());
  }

}

When I have string like "2011-06-12" as input in myDate I will get output "Thu Sep 29 00:00:00 EEST 2011", which is good.

When I sent an incorrect string like “2011-0612”, I’m getting error as expected.

Problems start when I’m trying to pass a string which still has two “hyphens”, but number of digits is wrong. Example:

input string “2011-06-1211” result "Tue Sep 23 00:00:00 EEST 2014".

input string “2011-1106-12” result "Mon Feb 12 00:00:00 EET 2103".

I can't change input format of string date.

How I can avoid it?

Answer

Jon Skeet picture Jon Skeet · May 15, 2012

Have you tried calling setLenient(false) on your SimpleDateFormat?

import java.util.*;
import java.text.*;

public class Test {

    public static void main(String[] args) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        Date date = format.parse("2011-06-1211"); // Throws...
        System.out.println(date);
    }
}

Note that I'd also suggest setting the time zone and locale of your SimpleDateFormat. (Alternatively, use Joda Time instead...)