Stats

270 Contributors: 20
2017-07-27
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Date Class

Download java eBook

Syntax

  • Date object = new Date();
  • Date object = new Date(long date);

Parameters

ParameterExplanation
No parameterCreates a new Date object using the allocation time (to the nearest millisecond)
long dateCreates a new Date object with the time set to the number of milliseconds since "the epoch" (January 1, 1970, 00:00:00 GMT)

Remarks

Representation

Internally, a Java Date object is represented as a long; it is the number of milliseconds since a specific time (referred to as the epoch). The original Java Date class had methods for dealing with time zones, etc., but these were deprecated in favor of the then-new Calendar class.

So if all you want to do in your code is represent a specific time, you can create a Date class and store it, etc. If you want to print out a human-readable version of that date, however, you create a Calendar class and use its formatting to produce hours, minutes, seconds, days, time zones, etc. Keep in mind that a specific millisecond is displayed as different hours in different time zones; normally you want to display one in the "local" time zone, but the formatting methods have to take into account that you may want to display it for some other one.

Also be aware that the clocks used by JVMs do not usually have millisecond accuracy; the clock might only "tick" every 10 milliseconds, and therefore, if timing things, you cannot rely on measuring things accurately at that level.

Import Statement

import java.util.Date;

The Date class may be imported from java.util package.

Caution

Date instances are mutable, so using them can make it difficult to write thread-safe code or can accidentally provide write access to internal state. For example, in the below class, the getDate() method allows the caller to modify the transaction date:

public final class Transaction {
  private final Date date;

  public Date getTransactionDate() {
    return date;
  }
}

The solution is to either return a copy of the date field or use the new APIs in java.time introduced in Java 8.

Most of the constructor methods in the Date class have been deprecated and should not be used. In almost all cases, it is advisable to use Calendar class for date operations.

Java 8

Java 8 introduces new time and date API in the package java.time, including LocalDate and LocalTime. The classes in the java.time package provide an overhauled API that is easier to use. If you are writing to Java 8 it is strongly encouraged that you use this new API. See Dates and Time (java.time.*) .

Related Examples