O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required