Java Program To Calculate Days Between Two Dates
Chapter:
Date and Time
Last Updated:
16-04-2023 12:28:08 UTC
Program:
/* ............... START ............... */
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
String date1String = "2022-01-01";
String date2String = "2022-01-15";
LocalDate date1 = LocalDate.parse(date1String);
LocalDate date2 = LocalDate.parse(date2String);
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
System.out.println(daysBetween);
}
}
/* ............... END ............... */
Output
Notes:
-
In this example, we first define two dates as strings in the format "YYYY-MM-DD" using the variables date1String and date2String. In this case, date1String is set to "2022-01-01" and date2String is set to "2022-01-15".
- Next, we use the LocalDate.parse method to parse the date strings and convert them into LocalDate objects. We store these objects in the variables date1 and date2.
- To calculate the number of days between the two dates, we use the ChronoUnit.DAYS.between method. This method takes two LocalDate objects as arguments and returns the number of days between them as a long value.
- Finally, we print the number of days between the two dates to the console using the System.out.println method. In this case, the output will be "14".
Tags
Java Program To Calculate Days Between Two Dates #How to calculate the days between to dates in java