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. |