Search code examples
javasimpledateformat

SimpleDateFormat problems with 2 year date


I'm trying to understand two things:

  1. Why doesn't the following code throw an exception (since the SimpleDateFormat is not lenient)
  2. It doesn't throw an exception, but why is it parsing the year as 0013 (instead of using the rules here the +80:-20 years from today rule)

Here's the code

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestDate {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        format.setLenient(false);
        Date date = format.parse("01/01/13"); // Since this only has a 2 digit year, I would expect an exception to be thrown

        System.out.println(date); // Prints Sun Jan 01 00:00:00 GMT 13

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        System.out.println(cal.get(Calendar.YEAR)); // Prints 13
    }
}

If it makes a difference, I'm using java 1.6.0_38-b05 on Ubuntu


Solution

  • SimpleDateFormat API:

    For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.

    As for lenient, when it's set to false parse throws exception for invalid dates, eg 01/32/12, while in lenient mode this date is treated as 02/01/12. SimpleDateFormat uses Calendar internally, details about leniency can be found in Calendar API.