Write a Java program to calculate the difference between two dates in days?
This Java program calculates the number of days between two dates.
- 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 consider 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.
import java.time.*; 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
This program calculates the difference in days between two dates. The program uses the Java time library to access the current date and time, and to perform the date calculations.
The program first creates two Calendar objects, representing the two dates whose difference is to be calculated. The set() method sets the year, month, and day of the two calendars.
Next, the program calculates the difference between the two dates in milliseconds using the getTimeInMillis() method of the Calendar class. This difference is then converted to days using the TimeUnit class, which provides a convenient way to convert between different units of time.
Finally, the program prints the difference in days using the System.out.println() method.