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: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

So here is some code:

Here is the output:

I honestly wasted about 5 minutes at first because I was trying to force Ruby into the Java code (by trying Date theDate = Date.new()) 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.