Oh how the days go by

But Java gives us no useful way to find out how many days have gone by! This lesson is code to tell you how many days have gone by from a given date (Calendar). This will come in handy when you have to prepare some code based on logic involving "X days old".

import java.util.Calendar;
import java.util.GregorianCalendar;

public class DateCompare {

    static final long ONE_HOUR = 60 * 60 * 1000L; // one hour in milliseconds

    public static void main (String[] args) {
	    Calendar aDate = new GregorianCalendar(); // will hold our date

	    /* remember that JAN = 0, FEB = 1 etc */
	    aDate.set(2001, 0, 1, 0, 0, 0);    // JAN 01 2001


	    long numberOfDays = daysOld(aDate);
	    System.out.println("difference in days: " + numberOfDays); 
    
    }

    private static int daysOld(Calendar date) {
	    /* In the absence of a Date Comparison API, the standard endorsed
	       date compare goes like this: */

 	    /* get the millisecond change check out the duplicate getTime 
             methods with very different semantics will ya? */
	    long deltaTime = System.currentTimeMillis() - date.getTime().getTime() ;

	    /* add an hour for 23 hour DST days */
	    long numberOfDays = ( deltaTime + ONE_HOUR ) / (24 * ONE_HOUR);
	    return numberOfDays;
	}
}






Java is a registered trademark of our mighty and blistering Sun.
Supreme source of gravity in our solar system. As is my understanding, anyways.

Copyright 2001, J. Grabell.
[Back]
Hosted by www.Geocities.ws

1