验证日期月份和年份

dan*_*dan 0 php

我的日期格式为 MM-YYYY(例如:04-2000)。我将日期分解为月份和年份,现在尝试检查该月份的某些条件:

  • 1 到 12 之间
  • 由2位数字组成)

以及年份:

  • 由4位数字组成

我的语法正确吗?

list($name_month, $name_year) = explode('-', $name_date, 2);
if(($name_month < 1 || $name_month > 12 || $name_month ) || ($name_year)) {
    echo "<br><br>Wrong date";
    $uploadOk = 0;}
Run Code Online (Sandbox Code Playgroud)

Geo*_*rge 5

您可以使用 DateTime 对象并createFromFormat()验证您的日期:

$date = '04-2000';

// Create a DateTime object pointing to the 1st of your given month and year
$d = DateTime::createFromFormat('d-m-Y', '01-' . $date);
if($d && $d->format('m-Y') == $date){
  echo 'Valid date';
}
Run Code Online (Sandbox Code Playgroud)

评估版

  • - **这个答案不正确**,当当天是 28 号之后时,会失败并显示 `$date = '02-2015'`...孩子们不要在家里使用它! (3认同)