w3resource

PHP Date Exercises : Time difference in days and years, months, days, hours, minutes, seconds between two dates

PHP date: Exercise-11 with Solution

Write a PHP script to get time difference in days and years, months, days, hours, minutes, seconds between two dates.

Note : Use DateTime class.

Sample Solution:

PHP Code:

<?php
$date1 = new DateTime('2012-06-01 02:12:51'); // Creating a DateTime object for the first date.
$date2 = $date1->diff(new DateTime('2014-05-12 11:10:00')); // Calculating the difference between two dates.
echo $date2->days.'Total days'."\n"; // Outputting the total number of days between the two dates.
echo $date2->y.' years'."\n"; // Outputting the number of years in the difference.
echo $date2->m.' months'."\n"; // Outputting the number of months in the difference.
echo $date2->d.' days'."\n"; // Outputting the number of days in the difference.
echo $date2->h.' hours'."\n"; // Outputting the number of hours in the difference.
echo $date2->i.' minutes'."\n"; // Outputting the number of minutes in the difference.
echo $date2->s.' seconds'."\n"; // Outputting the number of seconds in the difference.
?>

Output:

710Total days                                               
1 years                                                     
11 months                                                   
10 days                                                     
8 hours                                                     
57 minutes                                                  
9 seconds

Explanation:

In the exercise above,

  • $date1 = new DateTime('2012-06-01 02:12:51');: Create a DateTime object representing June 1, 2012, at 02:12:51.
  • $date2 = $date1->diff(new DateTime('2014-05-12 11:10:00'));: Calculates the difference between the DateTime object $date1 and the date May 12, 2014, at 11:10:00.
  • $date2->days: Get the total number of days in the difference between the two dates.
  • $date2->y, $date2->m, $date2->d, $date2->h, $date2->i, $date2->s: Get the number of years, months, days, hours, minutes, and seconds in the difference, respectively.

Flowchart :

Flowchart: Time difference in days and years, months, days, hours, minutes, seconds between two dates

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to check whether the given dates are valid or not?
Next: Write a PHP script to change month number to month name.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-date-exercise-11.php