Getting the difference between two dates times
suggest changeUse the DateTime class.
An example:
<?php
// Create a date time object, which has the value of ~ two years ago
$twoYearsAgo = new DateTime("2014-01-18 20:05:56");
// Create a date time object, which has the value of ~ now
$now = new DateTime("2016-07-21 02:55:07");
// Calculate the diff
$diff = $now->diff($twoYearsAgo);
// $diff->y contains the difference in years between the two dates
$yearsDiff = $diff->y;
// $diff->m contains the remaining months, not the total months and not minutes
$monthsDiff = $diff->m;
// $diff->d contains the difference in days between the two dates
$daysDiff = $diff->d;
// $diff->h contains the difference in hours between the two dates
$hoursDiff = $diff->h;
// $diff->i contains the difference in minutes between the two dates
$minsDiff = $diff->i;
// $diff->s contains the difference in seconds between the two dates
$secondsDiff = $diff->s;
// $diff->days is the total number of days. y, m, d, h, i, and s are leftover parts, not totals.
$totalDaysDiff = $diff->days;
// Dump the diff altogether just to get some details ;)
var_dump($diff);
DateTime objects can be compared with the comparison operators:
<?php
// Create a date time object, which has the value of ~ two years ago
$twoYearsAgo = new DateTime("2014-01-18 20:05:56");
// Create a date time object, which has the value of ~ now
$now = new DateTime("2016-07-21 02:55:07");
var_dump($now > $twoYearsAgo); // prints bool(true)
var_dump($twoYearsAgo > $now); // prints bool(false)
var_dump($twoYearsAgo <= $twoYearsAgo); // prints bool(true)
var_dump($now == $now); // prints bool(true)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents