Date class

The class Date represents a specific instant in time, with millisecond precision.

The following representations are used when accepting or returning year, month, date, hours, minutes, and seconds values.

  • A year y is represented by the integer y - 1900.
  • A month is represented by an integer from 0 to 11; 0 is January, 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • An hour is represented by an integer from 0 to 23. hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
  • A minute is represented by an integer from 0 to 59.
  • A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds.

A date may be specified as January 32 and is interpreted as meaning February 1.

Constructors

Date()
Creates a Date object and initializes it with the time at which it was allocated.
Date(long date)
Creates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Compare two Date value

boolean after(Date when)
Tests if this date is after the specified date.
boolean before(Date when)
Tests if this date is before the specified date.
int compareTo(Date anotherDate)
Compares two Dates for ordering.
boolean equals(Object obj)
Compares two dates for equality.

Convert date value to long value in milliseconds

long getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
void setTime(long time)
Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

Convert Date value to String

String toString()
Converts this Date object to a String of the form:

Revised from Open JDK source code

Home 
  Java Book 
    Essential Classes  

Date:
  1. Date class
  2. Create Date object
  3. Compare two Date value
  4. Convert date value to long value in milliseconds
  5. Convert Date value to String