Skip to content

SimpleDateFormat and the 13th month

Wow. I just learned something about SimpleDateFormat, a class that I always resort to when I have to convert a String to a Date in java. Check out this bit of code:

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

public class foo {
public static void main (String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
System.out.println("12012000 "+ sdf.parse("12012000"));
System.out.println("13012000 "+ sdf.parse("13012000"));
System.out.println("12322000 "+ sdf.parse("12322000"));
}
}

and the output from that code:

$ java -classpath . foo
12012000 Fri Dec 01 00:00:00 MST 2000
13012000 Mon Jan 01 00:00:00 MST 2001
12322000 Mon Jan 01 00:00:00 MST 2001

Any overflow gets rolled into the the next higher, well, in addition, I’d call this a place. The 32nd day of December is the 1st of Jan, and the 13th month of any year is Jan. This is an implementation detail, as I found no mention of it in the SimpleDateFormat javadoc, nor the DateFormat javadoc, but others have noticed this too.

3 thoughts on “SimpleDateFormat and the 13th month

  1. Tom Malaher says:

    You can turn this off if you don’t like it:

    setLenient(boolean)

    Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object’s format. With strict parsing, inputs must match this object’s format.

  2. Dan Moore says:

    Cool! Thanks Tom.

    Output from the above program after inserting

    sdf.setLenient(false);
    after instantiating sdf:

    Exception in thread “main” java.text.ParseException: Unparseable date: “13012000” at java.text.DateFormat.parse(DateFormat.java:334)
    at foo.main(foo.java:8)

Comments are closed.