php

Calculate days between two dates in PHP

Spread the love

How to Calculate days between two dates in PHP –

Calculate days between two dates is very easy task in PHP given as examples bellow –

Example – 1 : In this example, the days are calculated from the current date.

  • The time() function returns the current time as a Unix timestamp.
  • The strtotime() function is PHP predefined function which is parse an English textual datetime into a Unix timestamp (no. of seconds since January 1 1970 00:00:00 GMT).
  • The round() function returns a floating-point number (UP to the nearest integer).
<?php
date_default_timezone_set('Asia/Kolkata'); // set time zone of India (GMT+5:30)

$currentDate = time(); // convert current date & time to Unix timestamp
$yourDate = strtotime("2020-04-01"); // from date

$dateDiff = $currentDate - $yourDate; // no. of seconds
$totalDays = round($dateDiff / (60 * 60 * 24)); // return UP to the nearest integer

echo "Total Days = ".$totalDays;
?>

Output : Total Days = 756

Example – 2 : In this example, the days are calculated between two dates.

<?php
date_default_timezone_set('Asia/Kolkata'); // set time zone of India (GMT+5:30)

$firstDate = strtotime("2020-04-01"); // first date
$secondDate = strtotime("2020-04-30"); // second date

$dateDiff = $secondDate - $firstDate; // no. of seconds
$totalDays = round($dateDiff / (60 * 60 * 24)) + 1; // including one day

echo "Total Days = ".$totalDays;
?>

Output : Total Days = 30

Read more…

Calculate days between two dates in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *