-3

I want to create a function, to check if $date is a valid date and time

function validateDate($date){
    $format = 'Y-m-d h:i A';// Eg : 2014-09-24 10:19 PM
    ....
}

I want to check the $date is valid, and it is in given format:

  • If the statement is true {
        function should return corresponding time() of the date using strtotime() or any other functions,,
    }

  • Otherwise {
        return false
    }

You may suggest me to use regex. But I think it have limitation in the case of feb,april,june,sep,nov etc.

I found a code to check if the date is valid.

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

function was copied from this answer or php.net

But I didn't understood it's logic.

Community
  • 1
  • 1
  • You found this one didn't you http://stackoverflow.com/a/19271434/ - I'm tempted to vote to close this as an exact duplicate. See also http://stackoverflow.com/questions/14504913/verify-valid-date-using-phps-datetime-class – Funk Forty Niner Sep 24 '14 at 16:59

1 Answers1

4
function validateDate($date) {
    $format = 'Y-m-d h:i A'; // Eg : 2014-09-24 10:19 PM
    $dateTime = DateTime::createFromFormat($format, $date);

    if ($dateTime instanceof DateTime && $dateTime->format('Y-m-d h:i A') == $date) {
        return $dateTime->getTimestamp();
    }

    return false;
}
Weltschmerz
  • 2,166
  • 1
  • 15
  • 18
  • Warning: Unexpected character in input: '\' (ASCII=92) state=1 on line 4 Warning: Unexpected character in input: '\' (ASCII=92) state=1 on line 6 Fatal error: Call to undefined method DateTime::createfromformat() on line 4 – Shameel Kadannamanna Sep 24 '14 at 17:16
  • Thankyou , I am 15 yr old.. Can you explain the different keywords, operators , functions used in the code above – Shameel Kadannamanna Sep 24 '14 at 17:26