Printing Date/Time in a Specified Format

Problem

You want to print the date and/or time in a specified format.

Solution

Use a java.text.DateFormat.

Discussion

To print the date in the correct format for whatever locale your software lands in, simply use the default DateFormat formatter, which is obtained by calling DateFormat.getInstance( ) .

Suppose you want the date printed, but instead of the default format “Sun Jul 18 16:14:09 PDT 1999”, you want it printed like “Sun 1999.07.18 at 04:14:09 PM PDT”. A look at the Javadoc page for SimpleDateFormat -- the only non-abstract subclass of DateFormat -- reveals that it has a rich language for specifying date and time formatting. To use a default format, of course, we can just use the Date object’s toString( ) method, and for a localized default format, we use DateFormat.getInstance( ). But to have full control and get the “Sun 1999.07.18 at 04:14:09 PM PDT”, we construct an instance explicitly, like so:

new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

E means the day of the week; yyyy, MM, and dd are obviously year, month, and day. The quoted string 'at' means the string “at”. hh:mm:ss is the time; a means A.M. or P.M., and zzz means the time zone. Some of these are more memorable than others; I find the zzz tends to put me to sleep. Here’s the code:

// DateDemo.java Date dNow = new Date( ); /* Simple, Java 1.0 date printing */ System.out.println("It is now " + dNow.toString( )); // Use a SimpleDateFormat to print the date ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.