我从一个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 = \DateTime::createFromFormat('d/m/Y', $dataRowValue);
if (!empty($date)) {
//Your logic
}else{
//Error
}
如果您传递任何alpha或字母数字值,它将返回给您空值
其他回答
正则表达式的解决方案
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);
}
}
与cl-sah的回答一致,但这个听起来更好,更短…
function checkmydate($date) {
$tempDate = explode('-', $date);
return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}
Test
checkmydate('2015-12-01');//true
checkmydate('2015-14-04');//false
这个选项不仅简单,而且几乎可以接受任何格式,尽管使用非标准格式可能会有bug。
$timestamp = strtotime($date);
return $timestamp ? $date : null;
试一试:
$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";
}
/**** date check is a recursive function. it's need 3 argument
MONTH,DAY,YEAR. ******/
$always_valid_date = $this->date_check($month,$day,$year);
private function date_check($month,$day,$year){
/** checkdate() is a php function that check a date is valid
or not. if valid date it's return true else false. **/
$status = checkdate($month,$day,$year);
if($status == true){
$always_valid_date = $year . '-' . $month . '-' . $day;
return $always_valid_date;
}else{
$day = ($day - 1);
/**recursive call**/
return $this->date_check($month,$day,$year);
}
}