Recipe 6.8 Difference Between Two Dates


You need to compute the difference between two dates.


Convert to Date objects if necessary, call their getTime( ) methods, and subtract. Format the result yourself.


The API has no general mechanism for computing the difference between two dates. This is surprising, given how often it comes up in some types of commercial data processing. However, it's fairly simple to implement this yourself:

import java.util.*; /** DateDiff -- compute the difference between two dates. */ public class DateDiff {         public static void main(String[] av) {                 /** The date at the end of the last century */                 Date d1 = new GregorianCalendar(2000,11,31,23,59).getTime( );                 /** Today's date */                 Date today = new Date( );                 // Get msec from each, and subtract.                 long diff = today.getTime( ) - d1.getTime( );                 System.out.println("The 21st century (up to " + today +                          ") is " + (diff / (1000*60*60*24)) + " days old.");         } }

I'm editing this recipe in November of 2003; the 20th Century AD ended at the end of 2000, so the value should be about 3 11/12 years, and it is:

> java DateDiff The 21st century (up to Tue Nov 25 09:20:15 EST 2003) is 1058 days old.  >

You saw Calendar's add( ) method in Recipe 6.7, but that only adds to the day, month, or year (or any other field) in the Calendar object; it does not add two Calendar dates together.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: