验证输入是YYYY-MM-DD HH:mm:ss格式?

I'm writing a PHP script that takes in a user entered value that MUST be something like this.

2011-06-17 00:00:00
...
2011-06-17 23:59:59

How do I verify that it is indeed a correct input?

Alternatively, use strtotime() on the input, and then date() to put it in your required format. This has the advantage of validating that the user provided a correct date, not just a correct format. I.e., a regex check won't catch when somebody puts in Feb 31.

$date = strtotime($input);
if ($date === false) {
    throw Exception('bad date');
}
$formatted = date('<whatever>', $date);

You're looking for validation for ISO 8601.

Here is a sample regular expression to validate that format:

^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$

http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/

or better yet,

Zend Framework Date Validation

Example:

$validator = new Zend_Validate_Date(array('format' => 'yyyy-MM-dd HH:mm:ss'))
$validator->isValid('2011-06-17 00:00:00');

use regular expressions: http://php-regex.blogspot.com/ and http://networking.ringofsaturn.com/Web/regex.php are good places to start learning

or use this solution:

$exploded = explode($INPUT_STRING, " ");
$date_explode = explode($exploded[0],"-");
$time_explode = explode($exploded[1],":");
if (empty($date_explode[0])||empty($date_explode[1])||empty($date_explode[2])||empty($time_explode[0])||empty($time_explode[1])||empty($time_explode[2])) {
die ("ERROR! Not correct input format!");
}

Use DateTime::createFromFormat and check for return value.

 $date = strtotime('2011-13-17 23:00:00');
 if($date){print("legal");}
/(\d{4}[\-]((0[1-9]|1[0-2]))[\-]((0[1-9]|1[0-9]|2[0-9]|3[0-1]))(([t-tT-T]|\s)((0[0-9]|1[0-9]|2[0-3]))[\:]((0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]))[\:]((0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]))([.][a-zA-Z0-9]*)?)?)$/i;

Its try for

2013-06-28 2013-06-28T13:35:59 2013-06-28 13:35:59 2013-06-28T13:35:59.000 2013-06-28 13:35:59.000 2013-06-28T13:35:59.000Z 2013-06-28 13:35:59.000Z

Its not simplified, although it can greatly be simplified..

For complete date/time verification, use both DateTime::createFromFormat() and strtotime(), such as

// Convert it to test if the datetime can be successfully used. Finer than regex.
$dateformat = DateTime::createFromFormat('Y-m-d H:i:s', '2014-09-27 20:00:05');
$datereal = strtotime($inputStart);

if( $dateformat === FALSE || $datereal === FALSE )
    echo "Invalid format/datetime".

If you want, you can divide the checks to post separate messages if the date is wrong format or simply impossible.