使用 checkdate() 函数检查日期是否有效的 PHP 程序


2022年3月22日, Learn eTutorial
1959

如何使用 PHP 检查输入的日期是否为有效日期?

在此程序中,我们使用内置函数 checkdate() 来检查用户输入的日期是否为有效日期。首先,我们从用户那里接收日、月和年,并将它们分别赋给变量 s、my。之后,我们将内置函数 checkdate(m,d, y) 的结果(用于检查日期是否有效)赋给变量 date。然后,我们检查变量 date 的值,如果为 true,则打印输入的日期为有效日期,否则打印输入的日期为无效日期。例如,如果用户输入的值是:

date = 30

m>

year = 2021

众所周知,二月份只有28或29天,所以我们可以说输入的日期不是一个有效日期。

checkdate() 函数的语法


checkdate(month, day, year)
 

算法

步骤 1: 接收用户输入的日、月和年,并将其分别赋给变量 d、my

步骤 2: 将内置函数 checkdate(m,d, y) 的结果(用于检查日期是否有效)赋给变量 date

步骤 3: 检查变量 date 的值,如果为 true,则打印输入的日期为有效日期,否则打印输入的日期为无效日期

PHP 源代码

                                          <?php
$d = readline("Enter the date: ");
$m = readline("Enter the month: ");
$y = readline("Enter the year: ");
$date = checkdate($m, $d, $y);
if ($date)
    echo "The entered date $d-$m-$y is a valid date";
else
    echo "The entered date $d-$m-$y is not a valid date";
?>
                                      

输出

Example 1
Enter the date: 10
Enter the month: 11
Enter the year: 2003
The entered date 10-11-2003 is a valid date

Example 2
Enter the date: 23
Enter the month: 20
Enter the year: 2020
The entered date 23-20-2020 is not a valid date