PHP - How to Calculate Different Between Two DateTimes

Sovary May 30, 2022 371
1 minute read

We can find value of two different date time by calculation in PHP. Along explaination below you will understand how to calculate between two date with example. For example when user registered in your system with date of birth, to know how old are they? we have to know two date values to check.

How input/Output should look

Input: start_date: 1990-05-30 9:45:30 
       end_date: 2022-09-11 11:44:01

Output: 32 years, 3 months, 12 days, 2 hours, 59 minutes, 29 seconds

Implementation

Using date_diff() and diff() functions to find different between two dates. Function return DateInterval object if success and return false on failure.

Example

Procedural Style:

<?php
 
  // Creates DateTime objects
  $datetime1 = date_create('1994-01-01');
  $datetime2 = date_create('2022-05-21');
 
  // Calculates between two DateTime objects
  $interval = date_diff($datetime1, $datetime2);
 
  // x years x months x days
  echo $interval->format('%y years %m months %d days');
?>

 Output:

28 years 4 months 20 days

Object Oriented Style:

<?php
  $datetime_1="1994-01-01 9:45:30";
  $datetime_2="2022-05-21 11:44:01";

  // Creates DateTime objects
  $start_datetime = new DateTime($datetime_1); 
  $end_datetime = new DateTime($datetime_2);
  
  // check difference datetime
  $diff = $start_datetime->diff($end_datetime); 
  
  // print result in format
  echo $diff->format('%y years %m months %d days %H:%M:%s');
  
  echo "\nyear=>".$diff->y;// return years
  echo "\nmonth=>".$diff->m;// return months
  echo "\ndate=>".$diff->d;// return days
?>

Output:

28 years 4 months 20 days 01:04:31
year=>28
month=>4
date=>20

Hope it would help you.

PHP 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him