Some Info on Dates in Java

On Friday I was helping a Rubyist with some Clojure. She needed to format a date, and wanted to use some Java to do it. I sent her some info in an email, and thought that I would share it here.

If you are just going to get the current time and futz with its format, then using java.util.Date and java.text.SimpleDateFormat should be sufficient. There are a lot of deprecated methods in java.util.Date. Pretty much all of them are setters and the constructors for making a Date other than the instant it is created. If you need to change the fields, then you should use java.util.GregorianCalendar. If you need to use GregorianCalendar, then you could call the GregorianCalendar.getTime() method, which returns a java.util.Date object.

With java.text.SimpleDateFormat, you can either supply the format in the constructor, or with the “applyPattern” method. You use the usual y, M, d, etc for the formatting. Here is the formatting page:

So here is some code:

Date theDate = new Date();
GregorianCalendar gCal = new GregorianCalendar();
System.out.println( "Here is theDate: " + theDate );
System.out.println( "Here is theDate.toString(): " + theDate.toString() );
System.out.println( "Here is gCal.getTime(): " + gCal.getTime().toString() );
SimpleDateFormat sdf001 = new SimpleDateFormat();
System.out.println( "theDate with sdf001 default: " + sdf001.format(theDate) );
sdf001.applyPattern( "yyyy/MM/dd hh_mm_ss" );
System.out.println( "theDate with sdf001 with pattern yyyy/MM/dd hh_mm_ss: " + sdf001.format(theDate) );
SimpleDateFormat sdf002 = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
System.out.println( "theDate with sdf002 yyyy-MM-dd hh:mm:ss: " + sdf002.format(theDate) );

Here is the output:

Here is theDate: Sun Jul 29 18:02:16 CDT 2012
Here is theDate.toString(): Sun Jul 29 18:02:16 CDT 2012
Here is gCal.getTime(): Sun Jul 29 18:02:16 CDT 2012
theDate with sdf001 default: 7/29/12 6:02 PM
theDate with sdf001 with pattern yyyy/MM/dd hh_mm_ss: 2012/07/29 06_02_16
theDate with sdf002 yyyy-MM-dd hh:mm:ss: 2012-07-29 06:02:16

I honestly wasted about 5 minutes at first because I was trying to force Ruby into the Java code (by trying Date theDate = and not realizing why the compiler was not cooperating. Kind of like when I tried (x * n) in Clojure on Friday before I remembered it should be (* x n)

Image from an 11th century manuscript housed at Bavarian State Library, webpage information here, image from World Document Library, image assumed allowed under Fair Use.