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 milliseconds—each 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 ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.