Date Class
suggest changeSyntax
Date object = new Date();Date object = new Date(long date);
Parameters
| Parameter | Explanation |
|---|---|
| No parameter | Creates a new Date using the allocation time (to the nearest millisecond). |
long date |
Creates a new Date 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.
If all you need is a specific instant, you can create a Date and store it. Date has no formatter. Use a DateFormat, or read fields from a Calendar, to produce hours, minutes, seconds, days, and time zones. The same millisecond is a different clock time in different time zones. Formatting normally uses the default time zone, and it can use another one.
JVM clocks often tick more slowly than once per millisecond, sometimes only every 10 milliseconds or so. Do not rely on Date to measure intervals at millisecond accuracy.
Import Statement
import java.util.Date;
The Date class may be imported from java.util package.
Caution
Date instances are mutable. Sharing them makes thread safety harder, and a getter can hand out write access to internal state. In the class below, getTransactionDate() lets the caller 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 Date constructors are deprecated and should not be used. For calendar fields, use Calendar or, on Java 8 and later, java.time.
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 for Java 8, use this API. See the java.time documentation.