Saturday, November 16, 2024
Google search engine
HomeLanguagesProgram to find the number of days between two dates in PHP

Program to find the number of days between two dates in PHP

In this article, we will see how to get the date difference in the number of days in PHP, along with will also understand the various ways to get the total count of difference in 2 dates & see their implementation through the examples. We have given two dates & our task is to find the number of days between these given dates. For this, we will be following the below 2 methods:

Consider the following example:

Input : date1 = "2-05-2017"
        date2 = "25-12-2017"
Output: Difference between two dates: 237 Days
Explanation: Calculating the total number of days between the start & end date.

Note: The dates can be taken in any format. In the above example, the date is taken in dd-mm-yyyy format.

 

Method 1: Using strtotime() Function

This is a built-in function in PHP that is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in the English date-time description. The function returns the time in seconds since the Unix Epoch

Example 1: In this example, we have taken two dates and calculated their differences.

PHP




<?php
  
// Function to find the difference 
// between two dates.
function dateDiffInDays($date1, $date2) {
    
    // Calculating the difference in timestamps
    $diff = strtotime($date2) - strtotime($date1);
  
    // 1 day = 24 hours
    // 24 * 60 * 60 = 86400 seconds
    return abs(round($diff / 86400));
}
  
// Start date
$date1 = "17-09-2018";
  
// End date
$date2 = "31-09-2018";
  
// Function call to find date difference
$dateDiff = dateDiffInDays($date1, $date2);
  
// Display the result
printf("Difference between two dates: "
     . $dateDiff . " Days ");
?>


Output: 

Difference between two dates: 14 Days

 

Method 2: Using date_diff() Function

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.

Example: This example describes calculating the number of days between the 2 dates in PHP.

PHP




<?php
  
// Creates DateTime objects
$datetime1 = date_create('17-09-2018');
$datetime2 = date_create('25-09-2018');
  
// Calculates the difference between DateTime objects
$interval = date_diff($datetime1, $datetime2);
  
// Display the result
echo $interval->format('Difference between two dates: %R%a days');
?>


Output: 

Difference between two dates: +8 days

 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments