我从一个API接收到一个日期字符串,它的格式是yyyy-mm-dd。
我目前正在使用一个正则表达式来验证字符串格式,这是可以工作的,但我可以看到一些情况下,根据字符串,它可能是一个正确的格式,但实际上是一个无效的日期。例如,2013年13月1日。
在PHP中是否有更好的方法来获取一个字符串,如2013-13-01,并判断它是否是yyyy-mm-dd格式的有效日期?
我从一个API接收到一个日期字符串,它的格式是yyyy-mm-dd。
我目前正在使用一个正则表达式来验证字符串格式,这是可以工作的,但我可以看到一些情况下,根据字符串,它可能是一个正确的格式,但实际上是一个无效的日期。例如,2013年13月1日。
在PHP中是否有更好的方法来获取一个字符串,如2013-13-01,并判断它是否是yyyy-mm-dd格式的有效日期?
当前回答
试一试:
$date = "2017-10-01";
function date_checker($input,$devider){
$output = false;
$input = explode($devider, $input);
$year = $input[0];
$month = $input[1];
$day = $input[2];
if (is_numeric($year) && is_numeric($month) && is_numeric($day)) {
if (strlen($year) == 4 && strlen($month) == 2 && strlen($day) == 2) {
$output = true;
}
}
return $output;
}
if (date_checker($date, '-')) {
echo "The function is working";
}else {
echo "The function isNOT working";
}
其他回答
判断是否有字符串是日期
function checkIsAValidDate($myDateString){
return (bool)strtotime($myDateString);
}
恐怕大多数投票的解决方案(https://stackoverflow.com/a/19271434/3283279)不能正常工作。第四个测试用例(var_dump(validateDate('2012-2-25'));// false)是错误的。日期是正确的,因为它对应的格式- m允许一个月前导零或不前导零(参见:http://php.net/manual/en/datetime.createfromformat.php)。因此,日期2012-2-25的格式是Y-m-d,测试用例必须为真而不是假。
我认为更好的解决方案是测试可能的错误,如下所示:
function validateDate($date, $format = 'Y-m-d') {
DateTime::createFromFormat($format, $date);
$errors = DateTime::getLastErrors();
return $errors['warning_count'] === 0 && $errors['error_count'] === 0;
}
正则表达式的解决方案
function verify_date($date){
/* correct format = "2012-09-15 11:23:32" or "2012-09-15"*/
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])( (0[0-9]|[1-2][0-4]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]))?$/",$date)) {
return true;
} else {
die("Wrong date format: it should be '2012-09-15 11:23:32' or '2012-09-15', date received is: ".$date);
}
}
试试这个:
$myday = '2022-1-30';
if (($timestamp = strtotime($myday)) === false) {
echo 'The string ('.$myday.') is not date';
} else {
echo 'The string ('.$myday.') is date = ' . date('l dS \o\f F Y h:i:s A', $timestamp);
}
试一试:
$date = "2017-10-01";
function date_checker($input,$devider){
$output = false;
$input = explode($devider, $input);
$year = $input[0];
$month = $input[1];
$day = $input[2];
if (is_numeric($year) && is_numeric($month) && is_numeric($day)) {
if (strlen($year) == 4 && strlen($month) == 2 && strlen($day) == 2) {
$output = true;
}
}
return $output;
}
if (date_checker($date, '-')) {
echo "The function is working";
}else {
echo "The function isNOT working";
}