Dates and Times

Java allows dates and times to be represented and manipulated in three forms: as long values or as java.util.Date or java.util.Calendar objects. Java 5.0 introduces the enumerated type java.util.concurrent.TimeUnit. The values of this type represent time granularities or units: seconds, milliseconds, microseconds, and nanoseconds. They have useful convenience methods but do not themselves represent a time value.

Milliseconds and Nanoseconds

At the lowest level, dates and times are represented as a long value that holds the positive or negative number of milliseconds since midnight on January 1, 1970. This special date and time is known as the epoch and is measured in Greenwich Mean Time (GMT) or Universal Time (UTC). To query the current time in this millisecond representation, use System.currentTimeMillis()

long now = System.currentTimeMillis();

In Java 5.0 and later, you can use System.nanoTime() to query time in nanoseconds. This method returns a long number of nanoseconds long. Unlike currentTimeMillis( ), the nanoTime() does not return a time relative to any defined epoch. nanoTime() is good for measuring relative or elapsed time (as long as the elapsed time is not more than 292 years) but is not suitable for absolute time:

long start = System.nanoTime();
long end = System.nanoTime();
long elapsedNanoSeconds = end - start;

The Date Class

java.util.Date is an object wrapper around a long that holds a number of milliseconds since ...

Get Java in a Nutshell, 5th Edition now with O’Reilly online learning.

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