PHP Program to find difference between two dates using date_diff() function

How to find the difference between two dates using the date_diff() in PHP?

In this program, we are going to find the days between two dates. For that, we are first reading the two dates from the user and assign them to the variables d1 and d2. Then change the value of the variable d1 and d2 to date using the built-in function date_create() and assign it to the variables date1 and date2. After that, we can find the difference between the two dates by using the built-in function date_diff(date1, date2) and assign the value to the variable d. And at last, we can Print the difference between the two dates in the variable d by using the method format("%R%a days")

Syntax date_fiff() function


date_diff(datetime1, datetime2, absolute)
 

Syntax date_create() function


date_create(time, timezone)
 

 

ALGORITHM

Step 1: Accept two days(in format "yyyy-mm-dd") from the user and assign it to the variable d1 and d2

Step 2: Change the value of the variable d1 to date using built-in function date_create() and assign it to the variable date1

Step 3: Change the value of the variable d2 to date using built-in function date_create() and assign it to the variable date2

Step 4: Find the difference between the two dates by using the built-in function date_diff(date1, date2) and assign the value to the variable d

Step 5: Print the difference between the two dates in the variable d by using the method format("%R%a days")

PHP Source Code

                                          <?php
$d1 = readline("Enter the date(yyyy-mm-dd): ");
$d2 = readline("Enter the date(yyyy-mm-dd): ");
$date1 = date_create($d1);
$date2 = date_create($d2);
$d = date_diff($date1, $date2);
echo $d->format("The difference is %R%a days");
?>
                                      

OUTPUT

Enter the date(yyyy-mm-dd): 2020-07-12
Enter the date(yyyy-mm-dd): 2020-12-07
The difference is +148 days