How to Calculate the Number of Days Between a Given Date Range in Java Code

Written by jonah quant
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Calculate the Number of Days Between a Given Date Range in Java Code
You can calculate the number of days within known dates. (Thinkstock Images/Comstock/Getty Images)

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:
Moderate

Other People Are Reading

Instructions

  1. 1

    Include the following line at the beginning of your Java code:

    import java.util.*;

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

  3. 3

    Compute the number of milliseconds elapsed between the two dates by using the .get Time() method, as in the following sample code:

    long millisElapsed;

    millisElapsed = (finalDate.getTime()).get Time() - (initialDate.getTime()).get Time();

  4. 4

    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.

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.