java util date class

java.util.Date

The Date class is available in java.util package. It represents a specific instant in time with millisecond precision.

Date class supports following two constructors:

  1. Date(): It initializes the object with the current date and time.
  2. Date(long millisec): initializes the object with the specified number of milliseconds since January 1, 1970, 00:00:00 GMT.

Java Date Class Methods

Method Description
boolean after(Date when) It returns true if the instant represented by this Date object is strictly later than the instant represented by when otherwise returns false.
boolean before(Date when) It returns true if the instant represented by this Date object is strictly earlier than the instant represented by when otherwise returns false.
Object clone() It duplicates the invoking Date object.
int compareTo(Date date) It returns 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
boolean equals(Object date) It returns true if both objects same long value from getTime method.
long getTime() It returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.
int hashCode() It returns a hash code value for this 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.
String toString() Converts this Date object to a String.

java.util.date class example

package com.w3schools;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class GetDateTime {
	public static void main(String args[]){
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
		String date = sdf.format(new Date()); 
		System.out.println(date);
	}
}

Output:

09-04-2018