﻿ PHP Class Exercise: Calculate the difference between two dates - w3resource

# PHP Class Exercises : Calculate the difference between two dates

## PHP class: Exercise-5 with Solution

Calculate the difference between two dates using PHP OOP approach.

Sample Dates : 1981-11-03, 2013-09-04

Sample Salution:

PHP Code:

``````<?php
// Create a new DateTime object representing the start date "1981-11-03"
\$sdate = new DateTime("1981-11-03");

// Create a new DateTime object representing the end date "2013-09-04"
\$edate = new DateTime("2013-09-04");

// Calculate the interval between the two dates
\$interval = \$sdate->diff(\$edate);

// Output the difference between the dates in years, months, and days
echo "Difference : " . \$interval->y . " years, " . \$interval->m . " months, " . \$interval->d . " days ";
?>
```
```

Output:

```Difference : 31 years, 10 months, 1 days
```

Explanation:

In the exercise above,

• \$sdate = new DateTime("1981-11-03");: This line creates a new DateTime object named '\$sdate' representing the start date "1981-11-03".
• \$edate = new DateTime("2013-09-04");: This line creates a new DateTime object named '\$edate' representing the end date "2013-09-04".
• \$interval = \$sdate->diff(\$edate);: This line calculates the difference between the start date '\$sdate' and the end date '\$edate' using the "diff()" method, and stores the result in the variable '\$interval'.
• echo "Difference : " . \$interval->y . " years, " . \$interval->m . " months, " . \$interval->d . " days ";: This line outputs the difference between the two dates in years, months, and days by accessing the properties \$interval->y (years), \$interval->m (months), and \$interval->d (days) of the "\$interval" object.

Flowchart :

PHP Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿