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

14

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

Similar Programs Chapter Last Updated
Java Date Format AM PM Date and Time 14-05-2023
Java Add Months To Date Date and Time 14-05-2023
Add Days To Date In Java example Date and Time 14-05-2023
Java Program To Add Days To Date Date and Time 16-04-2023
How To Find Difference Between Two Dates In Java Date and Time 01-04-2023
Add Days To Date Java Example Date and Time 08-08-2021
Time Difference Between Two Timestamps In Java Date and Time 22-09-2018

1