简体   繁体   中英

How do you validate a date format?

I want my users to be able to change the date format to whatever they like:

$dateformat = $_POST['format'];
$datestamp = date($dateformat,$timestamp);

How do I check if $dateformat is a correct valid date format string?

if( strtotime($_POST['format']) !== FALSE)
{
    echo 'valid date';
}
else
{
   echo 'invalid date';
}

But will not work on dates having year > 2048 as not defined in current PHP

checkdate() will tell you whether the date can be parsed should you decide to stick with a certain format:

strtotime() will let you know if a date string can be parsed - you can pass it any string. If the date cannot be parsed, the function returns false.

As a side note: I wouldn't let the user choose how to enter dates. This will make it very complicated for you, obviously - but also as user I would ask myself how I am supposed to enter the date, since most of the users will be used to instruction with regard to dates. Why not provide them with a simple drop down for year, month and date, and then use these three parameters with checkdate()?

I'd recommend you provide your users with a select drop down of various date formats then storing it in a database. You can then pull their selected format and insert it into the first parameter of the date() function.

Have a look into Zend_Date, but without knowing to interpret 06-03-2012 as 6th march or 3rd june it is not possible.

You know? 12/12/12 is the date, were the europeans and the americans can talk about the day without misunderstanding ;-)

Here's a regex implementation:

$input = 'M d Y';
if(preg_match('#(dd|DD|m|M|mm|MM|y|yy|YY|-|\s)+#', $input)) {
    $valid = true;
    print date($input);
} else {
    print "invalid date format";
}

It assumes that the space char and dash chars are allowed.

It specifies flags listed here: http://php.net/manual/en/datetime.formats.date.php

More here: http://php.net/manual/en/function.date.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM