- Home
- Technology
- How to calculate the differenc ...
In this tutorial, we are going to calculate the number of days between two given dates using PHP.
Let’s dive right in. A bit about the problem we want to solve. We have two dates date1 and date2.
Where date1 = 2020–05–01 and
date2 = 2020–02–21 and the task is to calculate the number of days between the two days.
We will make use of the strtotime() function. “strtotime — Parse about any English textual datetime description into a Unix timestamp”
The strtotime() function returns a timestamp if a valid date/time string is passed to it.
$date1 = strtotime("2020-05-01");
$date2 = strtotime("2020-02-21");
$diff = abs(($date2 - $date1)/60/60/24);
echo $diff;//output 69.958333333333
//69.958333333333 is the numbers of days between 2020-05-01 and 2020-02-21
Given date and time
$date1 = strtotime("2020-05-01 21:10:03");
$date2 = strtotime("2020-02-21 00:15:37");
$diff = abs(($date2 - $date1)/60/60/24);
echo $diff;
//output 70.829467592593
From the calculated number of days, you could pretty much get anything you want. Anything such as months, years, hours, etc. This is not the only method that can be used though, there are other ways this can be done too. Feel free to explore.
Happy coding.