我从一个API接收到一个日期字符串,它的格式是yyyy-mm-dd。

我目前正在使用一个正则表达式来验证字符串格式,这是可以工作的,但我可以看到一些情况下,根据字符串,它可能是一个正确的格式,但实际上是一个无效的日期。例如,2013年13月1日。

在PHP中是否有更好的方法来获取一个字符串,如2013-13-01,并判断它是否是yyyy-mm-dd格式的有效日期?


当前回答

使用php预构建函数的简单方式:

function checkmydate($date) {
  $tempDate = explode('-', $date);
  // checkdate(month, day, year)
  return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}

Test

   checkmydate('2015-12-01'); //true
   checkmydate('2015-14-04'); //false

其他回答

与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

判断是否有字符串是日期

function checkIsAValidDate($myDateString){
    return (bool)strtotime($myDateString);
}

试试这个:

$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";
}

恐怕大多数投票的解决方案(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;
}