JDK (Java Development Kit) Tutorials
Dr. Herong Yang, Version 5.00

java.util.Date - JDK Class to Measure Date and Time

This section provides a tutorial example on how to use the java.util.Date class to measure date and time. The Date class does not carry any calendar information.

Time usually refers to the hour, the minute and may be the second of a specific moment within a day. For example, if someone asks you: "What time is it?", you would answer: "It's nine thirty.", meaning that 9 hours and 30 minutes passed away since the beginning of the day.

Date usually refers to the calendar date of a specific day within a year. For example, if someone ask you: "What date is it today?", you would answer: "Today is October 25.", meaning that today is 21st day of the 10th month of this year.

So both terms: "time" and "date" are measurements of a specific moment. "Time" measures a specific moment with a unit of minute or second, using the beginning of the day as a reference point. "Date" measures a specific moment with a unit of day, using the beginning of the year as a reference point. Notice that these types of measurements are calendar and time zone dependent. At exactly the same moment, the values of "time" and "date" are different from one country to another.

In JDK, there is only one class, the Date class (java.util.Date), that measures a specific moment with a unit of millisecond, using a fixed moment of January 1, 1970, 00:00:00 GMT as a reference point.

The Date class measurement is calendar and time zone independent. So if you run the following code at exactly the same moment any where in the world, you will get exactly the same value:

   Date now = new Date(); // what time is it?
   long t = now.getTime(); 
   System.out.println("Time since 01-Jan-1970 00:00:00 GMT: " + 
      t + " milliseconds.");

Output:

Time since 01-Jan-1970 00:00:00 GMT: 1035236526708 milliseconds.

The Date class is very convenient for measuring a period of time:

   long t1 = (new Date()).getTime();
   // performing task XYZ
   long t2 = (new Date()).getTime();
   System.out.println("It took about " + ((t2-t1)/1000) + " seconds to"
      + " finish XYZ.");

However, the Date class does not provide any calendar and time zone related information. It requires the help of the Calendar class, see the next section.

The following is what you should remember about date and time in JDK:

  • The Date class actually measures time.
  • The Date class does not measure calendar date and hour.
  • There is no Time class.

Sections in This Chapter

java.util.Date - JDK Class to Measure Date and Time

java.util.Calendar - The Abstract Calendar Class

java.util.Calendar.add() - Calendar Manipulation Method

Dr. Herong Yang, updated in 2008
java.util.Date - JDK Class to Measure Date and Time