Chapter: Java The Complete Reference - The Java Library - java.util : More Utility Classes

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Date - java.util

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.

Date

 

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 non-deprecated constructors:

 

Date( ) Date(long millisec)

 

The first constructor initializes the object with the current date and time. The second constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970. The nondeprecated methods defined by Date are shown in Table 19-4. Date also implements the Comparable interface.



As you can see by examining Table 19-4, the non-deprecated Date features do not allow you to obtain the individual components of the date or time. As the following program demonstrates, you can only obtain the date and time in terms of milliseconds, in its default string representation as returned by toString( ), or (beginning with JDK 8) as an Instant object. To obtain more-detailed information about the date and time, you will use the Calendar class.

 

// 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);

 

}

 

}

Sample output is shown here:

 

Wed Jan 01 11:11:44 CST 2014

 

Milliseconds since Jan. 1, 1970 GMT = 1388596304803

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.