CheckDate 函数在无效时添加一个月份


CheckDate Function Adds a Month When Invalid

我正在根据日期确定星期几。 我添加了一个数组来打印出实际月份而不是月份的数字。 它可以在正确的日期正常工作。 但是当我查找无效日期时,checkdate 函数有效,但在显示无效日期时它会将月份向上移动一个。 我知道它与 monthName 有关,因为当我将其保留为月份编号 ($month) 时,它可以正常工作。 知道为什么吗?

<?Php
error_reporting(E_ALL ^ E_NOTICE);
$todo=$_POST['todo'];
if(isset($todo) and $todo=="submit")
    {
      $month=$_POST['month'];
      $dt=$_POST['dt'];
      $year=$_POST['year'];
      $timestamp = mktime(0, 0, 0, "$month", "$dt", "$year");
      $monthName = date("F", $timestamp);
        if (checkdate($month, $dt, $year)) 
            {
            "<br>";
            echo "$monthName $dt, $year was (or will be) on a " . 'date("l", mktime(0, 0, 0, "$month", "$dt", "$year")) . "<br>";
            } 
        else 
            {
            echo $error = "The date $monthName $dt, $year is invalid";
            }
      }
?>
<h2>Enter a Date and I'll Tell You the Day of the Week</h2>
<form method=post name=f1 action=''><input type=hidden name='todo' value="submit">
<table border="0" cellspacing="0" >
<tr><td  align=left>   
Month <select name=month value=''>Select Month</option>
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>...

如果您传递了一个无效的日期,那么我猜 mktime 会根据您传递的无效日期生成 $month + 1 的时间戳。 例如,2 月 30 日将转换为 3 月 1 日。

证明

就个人而言,我会放弃 mktime 并为此使用 DateTime。像这样:-

$month=2;
$dt=30;
$year=2014;
if(!checkdate($month, $dt, $year)){
    echo "$dt " . 'DateTime::createFromFormat('m', $month)->format('F') . " $year is not a valid date";
} else {
    $date = 'DateTime::createFromFormat('d m Y', "$dt $month $year");
    echo $date->format('jS F Y') . " will be a " . $date->format('l');
}

看到它工作