Calculating the number of days within a date range is a standard operation required by many computer programs. Java supports many varieties of formats and calculations on dates and times, through classes and methods in the Java standard libraries.
- Skill level:
Include the following line at the beginning of your Java code:
Create objects of the GregorianCalendar library class for the dates at the beginning and at the end of the range, as in the following sample code:
GregorianCalendar initial Date = new GregorianCalendar(2010,Calendar.MAY,20);
GregorianCalendar final Date = new GregorianCalendar(2011,Calendar.JUNE,4);
Replace the dates in the example -- May 20, 2010 and June 4, 2011 -- with the dates of your choice.
Compute the number of milliseconds elapsed between the two dates by using the .get Time() method, as in the following sample code:
millisElapsed = (finalDate.getTime()).get Time() - (initialDate.getTime()).get Time();
Convert milliseconds to days, as in the following sample code:
int day Elapsed = millisElapsed / (24 * 60 * 60 * 1000);
After executing this line, variable "dayElapsed" will contain the number of days in the date range.
- 20 of the funniest online reviews ever
- 14 Biggest lies people tell in online dating sites
- Hilarious things Google thinks you're trying to search for