Java2all.com  

Date class





Share This Topic -

Date class in java:

The Date classes encapsulate information about a specific date and time.

It provides the following constructors.

Date()

Date(long msec)

  • Here, the first form returns an object that represent the current date and time.
  • The second form returns an object that represents the date and time msec in milliseconds after the time.

The time is defined as midnight on January 1,1970 GMT (Greenwich Mean Time).

Method

Description

Boolean after(Date d)

Returns true if d is after the current date. Otherwise, returns false.

Boolean before(Date d)

Returns true if d is before the current date. Otherwise, returns false.

Boolean equals(Date d)

Returns true if d has the same value as the current date. Otherwise, returns false.

Long getTime()

Returns the number of milliseconds since the epoch.

Void setTime

(long msec)

Sets the date and time of the current object to represent msec milliseconds since the epoch.

String toString()

Returns the string equivalent of the date.

EX :

 import java.util.*;
public class Date_Demo
{
	public static void main(String args[])
	{
		Date dt = new Date();
		System.out.println(dt);
		
		Date epoch = new Date(0);
		System.out.println(epoch);
	}
}

 
Output :
 
Fri May 25 00:04:06 IST 2012
Thu Jan 01 05:30:00 IST 1970
 
EX :
 import java.util.Date;
public class date2 
{
	  public static void main(String[] args) 
	  {
	  
	    Date d1 = new Date();

	    try
	    {
	      Thread.sleep(1000);
	    }
	    catch(Exception e){}
	        
	    Date d2 = new Date();
	    
	    System.out.println("First Date : " + d1);
	    System.out.println("Second Date : " + d2);
	    System.out.println("Is second date after first ? : " + d2.after(d1));    

	  }
}

 
Output :
 
First Date : Fri May 25 00:06:46 IST 2012
Second Date : Fri May 25 00:06:47 IST 2012
Is second date after first ? : true
 
NOTE: learn about threadsleep and try catch
 
EX :
 import java.util.*;
public class date3
{

  public static void main(String args[])
  {

	  Date date = new Date();
	  System.out.println("Date is : " + date);
	  System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : " + date.getTime());
  
	  Date epoch = new Date(0);
	  date.setTime(10000);
	  System.out.println("Time after 10 second " + epoch);
	  System.out.println("Time after 10 second " + date);
	  String st = date.toString();
	  System.out.println(st);
  }

}

 
Output :
 
Date is : Fri May 25 00:12:52 IST 2012
Milliseconds since January 1, 1970, 00:00:00 GMT : 1337884972842
Time after 10 second Thu Jan 01 05:30:00 IST 1970
Time after 10 second Thu Jan 01 05:30:10 IST 1970
Thu Jan 01 05:30:10 IST 1970