Calculating the Difference Between Two Dates


long time1 = date1.getTime(); long time2 = date2.getTime(); long diff = time2  time1; System.out.println("Difference in days = "     + diff/(1000*60*60*24));



This phrase converts two date objects, date1 and date2, into millisecondseach represented as a long. The difference is calculated by subtracting time1 from time2. We then print out the calculated difference in days by performing the arithmetic necessary to convert the millisecond difference into days difference.

Many times, you will want to know the time difference between two dates. A good example of this is in calculating how many days are left before an item is set to expire. If you have the expiration date of an item, you can calculate the days until expiration by calculating the difference between the expiration date and the current date. Below, we show an example of a simple method for making this calculation:

public static void daysTillExpired(Date expDate) {     Date currentDate = new Date();     long expTime = expDate.getTime();     long currTime = currentDate.getTime();     long diff = expTime  currTime;     return diff/(1000*60*60*24); }


This method takes an expiration date as input, and calculates the number of days until the expiration date is reached. This value in days is returned from the method. This could be a negative number if the expiration date is in the past.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net