Lets talk about Calculating the Date and Time Difference using date_diff :
It is the most easy way to calculate Date and Time Difference in php .
General Syntax :
<?php date_diff($dt1, $dt2); ?>
Here ,
<?php $start_date = date_create('1985-11-30'); $end_date = date_create(); // Current time and date $diff = date_diff( $start_date, $end_date ); echo 'The difference is '; echo $diff->y . ' years, '; echo $diff->m . ' months, '; echo $diff->d . ' days, '; echo $diff->h . ' hours, '; echo $diff->i . ' minutes, '; echo $diff->s . ' seconds'; echo "<br/>" echo 'The difference in days : ' . $diff->days; ?>
Output : The difference is 32 years, 8 months, 30 days, 11 hours, 16 minutes, 25 secondsThe difference in days : 11960
Explanation:
The arguments, $datetime_start and $datetime_end must be an object of DateInterval class, and can be achieved using date_create() function.
The arguments supplied does not have the order from small to large , we can also add the large date to fitst and small date to last arguments , the result will be same
$diff = date_diff( $end_dt, $start_dt );
The result produce by the date_diff() is the DateInterval object , which have many properties and can be observed by echo <pre>; print_r ($diff)
Formatting the Output
DateInterval object as the result of date_diff() function has a method named format() that can be used to produce the output with a specific format, for example:
<?php $diff = date_diff( date_create('1985-11-30'), date_create() ); echo $diff->format('Your age is %Y years and %d days'); ?>
Output : Your age is 32 years and 30 days
Explanation:
In order to translate the date_diff() in to characters use percent sign (%) at begning as example from above %Y and %d
- Year : Y stands for the four-digit year, and y stands for the two digits of the years.
- Month : M stands for 2-digit month, and m stands for one-two digit months.
- Date : D stands for 2-digit dates, and d stands for one-two digit of the dates.
- Today : A stands for a total different time of day. Example:
$diff = date_diff(date_create (‘1985-11-30’), date_create ());
echo $diff->format (‘Your age is %a day’); // Your age is 11960 day
- Hours : H stands for 2 digit hours, and h stands for one-two digit hours.
- Minutes : I stands for 2 digit minutes, and i stands for one-two digit minutes.
- Seconds : S stands for 2 digit seconds, and s stands for one-two digit seconds.