April 11, 2004

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.

Posted by moore at April 11, 2004 08:07 AM | TrackBack

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


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.

Posted by: Tom Malaher at April 12, 2004 08:28 AM | Permalink

And, of course, all my nice A HREF went away.
The link was to:

Posted by: Tom Malaher at April 12, 2004 08:29 AM | Permalink

Cool! Thanks Tom.

Output from the above program after inserting

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)

Posted by: Dan Moore at April 12, 2004 04:48 PM | Permalink
© Moore Consulting, 2003-2006