PHP 5.3.3.
$olddate = '2014-04-30';
$newdate = '30/05/2014';
Is there a simple way to compare these dates (which one is more recent) without having to manipulate the strings or changing one strings format?
I'm looking for a one or two liner?
You can not compare values as string.
You can use \DateTime object or convert this times to integer (timestamp), and next compare.
$oldDate = \DateTime::createFromFormat('Y-m-d', $oldDate);
$newDate = \DateTime::createFromFormat('d/m/Y', $newDate);
if ($newDate > $oldDate) {
// Your action
} else {
// Your action
}
Use strtotime
, which is smart enough to automatically parse the string in common cases. According to the documentation,
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components.
Using DateTime
(documentation) is preferred to use for operations with time differences
$date_1 = new DateTime($olddate);
$date_2 = new DateTime($new_date);
$diff = $date_1->diff($date_2);
The above will return DateInterval object, which contains all the information you need(documentation)
It is also possible using strtotime, which just returns unix timestamps of your time.
$stamp_1 = strtotime($oldddate);
$stamp_2 = strtotime($newdate);
$diff = $stamp_2 - $stamp_1; // really any comparison here