Date class in java

The Date class encapsulates the current date and time. Before beginning our examination of Date, it is important to point out that it has changed substantially from its original version defined by Java 1.0. When Java 1.1 was released, many of the functions carried out by the original Date class were moved into the Calendar and DateFormat classes, and as a result, many of the original 1.0 Date methods were deprecated. Since the deprecated 1.0 methods should not be used for new code, they are not described here.

Date supports the following constructors:

Date( )

Date(long millisec)

The Nondeprecated Methods Defined by Date

 Method Description
 boolean after(Date date)Returns true if the invoking Date object contains a date that is
   later than the one specified by date. Otherwise, it returns false.
   
 boolean before(Date date)Returns true if the invoking Date object contains a date that is
   earlier than the one specified by date. Otherwise, it returns false.
   
 Object clone( )Duplicates the invoking Date object.
   
 int compareTo(Date date)Compares the value of the invoking object with that of date. Returns
   0 if the values are equal. Returns a negative value if the invoking
   object is earlier than date. Returns a positive value if the invoking
   object is later than date.
   
 boolean equals(Object date)Returns true if the invoking Date object contains the same time
   and date as the one specified by date. Otherwise, it returns false.
   
 long getTime( )Returns the number of milliseconds that have elapsed since
   January 1, 1970.
   
 int hashCode( )Returns a hash code for the invoking object.
   
 void setTime(long time)Sets the time and date as specified by time, which represents
   an elapsed time in milliseconds from midnight, January 1, 1970.
   
 String toString( )Converts the invoking Date object into a string and returns the result.

Show date and time using only Date methods

import java.util.Date;

class DateDemo {

public static void main(String args[]) {

//Instantiate a Date object Date date = new Date();

//display time and date using toString() System.out.println(date);

//Display number of milliseconds since midnight, January 1, 1970 GMT long msec = date.getTime();

System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);

}

}

Output

Mon Jan 01 16:28:16 CST 2007

Milliseconds since Jan. 1, 1970 GMT = 1167690496023

Leave a Comment