Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

java.util.Date — reading, changing, and comparing time

Date represents an instant with millisecond precision. Learn to read it with getTime(), change it with setTime(long), and compare it with equals(Object).

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new Date(long milliseconds)
long getTime()
void setTime(long time)
boolean equals(Object obj)

java.util.Date represents an instant, not just a calendar date. Date.getTime() returns a long: milliseconds since 1970-01-01 00:00:00 GMT. Negative values represent earlier instants.

Date.setTime(long) replaces the time in the existing object and returns void; it neither adds time nor creates a copy. Warning: the object is mutable.

The base implementation of Date.equals(Object) returns true only if the argument is an instance of Date and both objects return the same value from getTime(). Otherwise, including when the argument is null, it returns false. Subclasses can override this method. For example, calling equals(Object) on a java.sql.Timestamp with a plain java.util.Date as the argument returns false even if both objects return the same value from getTime().

These three methods are not deprecated, although many calendar-related methods of the class are deprecated. The example uses fixed values instead of the system clock.

Examples

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Date first = new Date(0L);
        Date second = new Date(0L);
        System.out.println(first.getTime());
        System.out.println(first.equals(second));
        second.setTime(1000L);
        System.out.println(second.getTime());
        System.out.println(first.equals(second));
        System.out.println(first.equals(null));
    }
}

Result

0
true
1000
false
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources