Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Finding Today’s Date

Problem

You want to find today’s date.

Solution

Use a Date object’s toString( ) method.

Discussion

The quick and simple way to get today’s date and time is to construct a Date object with no arguments in the constructor call, and call its toString( ) method:

// Date0.java 
System.out.println(new java.util.Date(  ));

However, for reasons just outlined, we want to use a Calendar object. Just use Calendar.getInstance().getTime( ), which returns a Date object (even though the name makes it seem like it should return a Time value[21]), and print the resulting Date object, either using its toString( ) method or a DateFormat object. You might be tempted to construct a GregorianCalendar object, using the no-argument constructor, but if you do this, your program will not give the correct answer when non-western locales get Calendar subclasses of their own (in some future release of Java). The static factory method Calendar.getInstance( ) returns a localized Calendar subclass for the locale you are in. In North America and Europe it will likely return a GregorianCalendar, but in other parts of the world it might (someday) return a different kind of Calendar.

Do not try to use a GregorianCalendar ’s toString( ) method; the results are truly impressive, but not very interesting. Sun’s implementation prints all its internal state information; Kaffe’s inherits Object’s toString( ), which just prints the class name and the hashcode. Neither is useful for our purposes.

// Date1,.javaj ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata