Monday, 30 October 2017

java.util.Date class in java

Date Class


Java provides the Date class available in java.util package, this class encapsulates the current date and time. 

This class represents date and time in java. 

It provides constructors and methods to deal with date and time in java.

The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface.

It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

After Calendar class, most of the constructors and methods of java.util.Date class has been deprecated.

Constructors


1). Date( )

This constructor initializes the object with the current date and time.


2). Date(long milliseconds)

Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.


Methods


1)boolean after(Date date)

It is used to tests if the current date is after the given date.

2)boolean before(Date date)
   

This method is used tests if the current date is before the given date.

3)Object clone()   


returns the clone object of the current date.

4)int compareTo(Date date) 
  

compares current date with given date.

5)boolean equals(Date date)   


compares current date with given date for equality.

6)static Date from(Instant instant)

   
Use : returns an instance of Date object from Instant date.

7)long getTime()   


Use : returns the time represented by this date object.

8)int hashCode()   


Use  :  returns the hash code value for this date object.

9)void setTime(long time)   


Use  : changes the current date and time to given time.

10)Instant toInstant()   


Use  : converts the current date into the Instant object.



Example - 1


import java.util.*;
class DateDemo
{
    public static void main(String args[])

    {
        Date today=new Date();
        Date e=new Date(0);
     
        System.out.println("Date"+today);
        System.out.println("Date"+e);

        long msec=today.getTimes();
        System.out.println("Milisecond"+msec);
       
        System.out.println("Before:"+today.before(e));
        System.out.println("After:"+today.after(e));
     }

Example - 2


long millis=System.currentTimeMillis();
java.util.Date date=new java.util.Date(millis);
System.out.println(date); 

















Popular posts