If I have two variables $startDate="YYYYmmdd"
and $endDate="YYYYmmdd"
, how can I get the number of days between them please?
Thank you.
The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.
Calculate the no. of days between two dates, divide the time difference of both dates by no. of milliseconds in a day (1000*60*60*24)
Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format. Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates. echo "$date1 is older than $date2" ; ?>
php function week_between_two_dates($date1, $date2) { $first = DateTime::createFromFormat('m/d/Y', $date1); $second = DateTime::createFromFormat('m/d/Y', $date2); if($date1 > $date2) return week_between_two_dates($date2, $date1); return floor($first->diff($second)->days/7); } $dt1 = '1/1/2014'; $dt2 = '12/31/2014'; ...
If you are using PHP 5.3, you can use the new DateTime
class:
$startDate = new DateTime("20101013");
$endDate = new DateTime("20101225");
$interval = $startDate->diff($endDate);
echo $interval->days . " until Christmas"; // echos 73 days until Christmas
If not, you will need to use strtotime
:
$startDate = strtotime("20101013");
$endDate = strtotime("20101225");
$interval = $endDate - $startDate;
$days = floor($interval / (60 * 60 * 24));
echo $days . " until Christmas"; // echos 73 days until Christmas
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With