PHP - How to Calculate Different Between Two DateTimes

Sovary May 30, 2022 505
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him