Java's java.util.Date

Jakob Jenkov
Last update: 2014-06-23

Java's java.util.Date class was one of Java's first date classes. Today most of the methods in the class are deprecated in favor of the java.util.Calendar class. You can still use the java.util.Date class to represent a date though.

Here is how to instantiate a java.util.Date instance:

java.util.Date date = new java.util.Date();

This Date instance contains the current time as its date and time.

You can access the date and time contained in a java.util.Date instance using the getTime() method, like this:

java.util.Date date = new java.util.Date();

long time = date.getTime();

You can also create a java.util.Date from a time in milliseconds, like this:

long now = System.currentTimeMillis();

java.util.Date date = new java.util.Date(now);

Comparing Dates

You can compare java.util.Date instance because the class implements the java.lang.Comparable interface. Here is how:

java.util.Date date1 = new java.util.Date();
java.util.Date date2 = new java.util.Date();

int comparison = date1.compareTo(date2);

The comparison follows the rules for the Comparable interface, meaning the compareTo() method returns:

  • An int larger than 0 if the date the method is called on is later than the date given as parameter.
  • An int value of 0 if the dates are equal.
  • An int value less than 0 if the date the method is called on is earlier than the date given as parameter.

java.util.Date also has two shortcut methods to do comparisons. These are before() and after() methods. Here are two examples of how to use them:

java.util.Date date1 = new java.util.Date();
java.util.Date date2 = new java.util.Date();

boolean isBefore = date1.before(date2);
boolean isAfter  = date1.after (date2);

Getting the Year, Month, Day of Month, Hour etc.

The methods to get the year, month, day of month, hour etc. are deprecated. Apparently the algorithms used internally were not entirely correct.

If you need to get or set the year, month, day of month etc. use a java.util.Calendar instead.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next