Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php check for a valid date, weird date conversions

Is there a way to check to see if a date/time is valid you would think these would be easy to check:

$date = '0000-00-00';
$time = '00:00:00';
$dateTime = $date . ' ' . $time;

if(strtotime($dateTime)) {
    // why is this valid?
}

what really gets me is this:

echo date('Y-m-d', strtotime($date)); 

results in: "1999-11-30",

huh? i went from 0000-00-00 to 1999-11-30 ???

I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?

Edit: People are asking what i'm running: Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux

like image 238
SeanDowney Avatar asked Sep 26 '08 19:09

SeanDowney


People also ask

How do you check whether a date is valid or not in PHP?

PHP checkdate() function returns a boolean value. This value is true if the given date is valid and, false if it is invalid.

How do you check if a date is a valid date?

call(d) method. If the date is valid then the getTime() method will always be equal to itself. If the date is Invalid then the getTime() method will return NaN which is not equal to itself. In this example, isValid() method is checking if the getTime() is equal to itself or not.

How can I get current date in YYYY MM DD format in PHP?

$date = date("yyyy-mm-dd", strtotime(now));


1 Answers

From php.net

<?php
function isValidDateTime($dateTime)
{
    if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
        if (checkdate($matches[2], $matches[3], $matches[1])) {
            return true;
        }
    }

    return false;
}
?>
like image 190
mk. Avatar answered Oct 04 '22 14:10

mk.