Skip to main content

Posts

Showing posts from September, 2022

PHP function to get difference between dates

 Below is a PHP function that calculates and displays the difference in days between two dates. This function will take two date strings as inputs, convert them to DateTime objects, and then calculate the difference in days. Here's how you can define and use the function: <?php // Calculate day difference function calculateDayDifference ( $date1 , $date2 ) { // Create DateTime objects for the two dates $datetime1 = new DateTime( $date1 ); $datetime2 = new DateTime( $date2 ); // Calculate the difference $interval = $datetime1 -> diff ( $datetime2 ); // Get the difference in days $days_interval = $interval -> days ; return $days_interval ; } // Example usage $date1 = "2023-07-01" ; $date2 = "2023-07-15" ; echo calculateDayDifference( $date1 , $date2 ); ?> Explanation: Creating DateTime Objects: new DateTime($date1): This converts the first date string into a DateTime object. new DateTime