0

I need to check if two strings I have are dates and if they are the same date. They come in different formats i.e.

DD-MM-YYYY and YYYY-MM-DD

I did something that works but looks cumbersome and was wondering if there was something more succint and clever

if ((substr($old, 0, 4) == substr($new, 6, 4) && substr($old, 5, 2) == substr($new, 3, 2) && substr($old, 8, 2) == substr($new, 0, 2) && strlen($new)==10 && strlen($old) == strlen($new) && strtotime($old) == strtotime($new))) {

As unlikey as it is, we could have literally the text "DD-MM-YYYY" and YYYY-MM-DD" but obviously they aren't dates but it would still pass the test

UPDATE

if ((strtotime($old)===strtotime($new) && DateTime::createFromFormat('Y-m-d', $old) !== FALSE && DateTime::createFromFormat('d-m-Y', $new) !== FALSE)) {
pee2pee
  • 3,619
  • 7
  • 52
  • 133

2 Answers2

2

Something like this? (modified from here)

function validate_date($date, $format = 'Y-m-d') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

if(validate_date($old) && $validate_date($new, 'd-m-Y') && strtotime($old) == strtotime($new)) {
    //do stuff
}
Kaboodleschmitt
  • 453
  • 3
  • 13
0

strtotime() will return false if it can't create a timestamp out of the provided string. So the following should work:

if ( strtotime($old) && strtotime($new) && strtotime($old) == strtotime($new) ) {
    echo 'Same date!';
}
Terminator-Barbapapa
  • 3,063
  • 2
  • 5
  • 16