How to Calculate the Number of Days Between a Given Date Range in Java Code
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.
Instructions
-
-
1
Include the following line at the beginning of your Java code:
import java.util.*;
-
2
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 initialDate = new GregorianCalendar(2010,Calendar.MAY,20);
GregorianCalendar finalDate = 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.
-
-
3
Compute the number of milliseconds elapsed between the two dates by using the .getTime() method, as in the following sample code:
long millisElapsed;
millisElapsed = (finalDate.getTime()).getTime() - (initialDate.getTime()).getTime();
-
4
Convert milliseconds to days, as in the following sample code:
int dayElapsed = millisElapsed / (24 * 60 * 60 * 1000);
After executing this line, variable "dayElapsed" will contain the number of days in the date range.
-
1
References
- Photo Credit Thinkstock Images/Comstock/Getty Images