how to calculate the difference between the two dates using collections in java
Previous | Home | Next |
In this example we are going to calculate the difference of the two given dates.
In this example we have created a class named CollectionExample in which we have created the Date objects and then displayed the difference between their dates.
In this example we have used the getTime() method on the Date object for getting the time. The general syntax of the getTime() is as follows,
Date getTime()
The above method returns a Date object representing the current calendar time values.
In this example we have created a Date object named date1 and initialized it with using the constructor of the GregorianCalnedar(int year, int month, int day, int hour, int minute).
We have also created another Date object named todaysdate which is initialized with the default constructor and then invoked the getTime() method on it. Then we have displayed the difference between the two days created.
package r4r.co.in;
import java.util.*;
public class CollectionExample
{
/**
* @param args
*/
public static void main(String args[])
{
Date date1= new GregorianCalendar(2009, 6, 4, 11, 47).getTime(); // this statement sets a date-time from which difference is to be calculate
System.out.println("Time set is given by: "+date1); // displaying the set date
Date todaysdate=new Date(); // creating the Date object
System.out.println("Todays time is given by: "+todaysdate); // displaying the today's date
long DateDifference=todaysdate.getTime()-date1.getTime(); // calculating the difference between the dates in long milliseconds
System.out.println("The difference between the two dates in milliseconds is given by: "+DateDifference); // displaying the date difference in milliseconds
System.out.println("The difference between the two dates is:"+(DateDifference/(1000*24*60*60))+"days"); // displaying the date difference in terms of days
}
}
The output of the above example is given below:
Time set is given by: Sat Jul 04 11:47:00 PDT 2009
Todays time is given by: Tue Nov 16 11:32:31 PST 2010
The difference between the two dates in milliseconds is given by: 43202731234
The difference between the two dates is:500days
Previous | Home | Next |