Write a Java program to calculate the difference between two dates in days


This Java program calculates the number of days between two dates using the Calendar class and TimeUnit enumeration from the java.util.concurrent package.

  • First, two Calendar objects are created using the Calendar.getInstance() method, which returns a Calendar object representing the current date and time in the default time zone. The set() method is used to set the year, month, and day of each Calendar object to the desired values.
  • Next, the difference between the two Calendar objects is calculated by subtracting the milliseconds of one Calendar object from the other and taking the absolute value. The Math.abs() method is used to ensure a positive value.
  • The TimeUnit.DAYS.convert() method is then used to convert the milliseconds difference to days. The resulting value is stored in a long variable called Days.
  • Finally, the number of days between the two dates is printed to the console using System.out.println().

Note that this approach calculates the difference between two dates as the number of 24-hour periods, and does not take into account daylight saving time or other factors that can affect the length of a day. For more precise date and time calculations, it is recommended to use the java.time package, which provides a more accurate and flexible API for working with dates and times.

Source Code

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
 
class Calculate_Days
{
 
	public static void main(String[] args)
	{
        Calendar cal1 = Calendar.getInstance();
        cal1.set(2022, 10, 1);
        Calendar cal2 = Calendar.getInstance();
        cal2.set(2023, 10, 1);
 
        long Ms = Math.abs(cal1.getTimeInMillis() - cal2.getTimeInMillis());
        long Days = Math.abs(TimeUnit.DAYS.convert(Ms, TimeUnit.MILLISECONDS));
 
        System.out.println("Difference in days is: " + Days);        
    }
}

Output

Difference in days is: 365

Example Programs