There are times you would want to work with dates in your application and finding the difference between two dates is quite common. Handling dates in any programming language is always a tedious process so let me make a part of that easy for you in this post.
We are going to use 2 built in functions that PHP provides
strtotime() - strtotime() converts a date into a Unix timestamp. The type of date formats that are allowed can be found in PHP's datetime documentation
round() - round() is a mathematical function that rounds up a floating point number to its nearest integer e.g round(4.5) = 5, round(3.4) = 3 etc
Let's see how we would use this 2 functions to get what we need
<?php
$start_date = "3rd August 2022";
$end_date = "15th August 2022";
// ts means timestamp
$start_ts = strtotime($start_date);
$end_ts = strtotime($end_date);
$diff = $end_ts - $start_ts;
echo round($diff / 86400); // returns 12, that is 12 days
So what exactly is happening?
- We create two variables to store the start & end dates we want to find the difference of.
- The strtotime() method converts the dates into a unix timestamp format. We need to convert these two dates so that we can get the no of seconds from 1st January 1970 to the two dates. This is a very important step.
- We substract the two dates from each other to get the difference in seconds.
- We then divide the difference by 86400. Why 86400?, because that is the number of seconds in a day (60 seconds x 60 minutes x 24 hours). Dividing the difference by the total number of seconds in a day gives us the no of days we are looking for.
- The last step is to round up the final answer into an integer.
You could even take this further and put it inside a function, so that it can be reusable in multiple places
<?php
function dateDiff($start, $end) {
$start_ts = strtotime($start);
$end_ts = strtotime($end);
$diff = $end_ts - $start_ts;
return round($diff / 86400);
}
This is quite easy and simple to build and has a lot of use cases where it is helpful. Do you have a better way of handling this issue?, i would like to know in the comments.
Top comments (0)