You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP日期格式异常与.length、isNaN语法报错问题求解

PHP代码两处错误排查解决方案

问题1:日期输出为Unix时间戳格式

错误原因:gmdate()函数参数顺序传反,该函数第一个参数需传入标准日期格式串,第二个参数才是Unix时间戳,你直接将strtotime()生成的时间戳传入了第一个参数位,导致输出不符合预期。
修复方案:将对应行代码替换为:

echo "Fecha de vuelta: ".gmdate('Y-m-d', strtotime($_GET['fechaalquiler']."+ 10 days"))."<br/>";

如果需要其他日期格式,可自行调整第一个参数的格式串,比如d/m/Y对应日/月/年格式。

问题2:.length与isNaN语法报错

错误原因:.length与isNaN都是JavaScript的语法,你当前编写的是PHP代码,PHP不支持该写法,因此静态校验报错。
修复方案:

  • 字符串长度获取替换为PHP内置函数strlen(),原$_GET['dni'].length修改为strlen($_GET['dni'])
  • 非数字判断替换为PHP内置函数!is_numeric(),原isNaN(substr(($_GET['dni']), 0, 8))修改为!is_numeric(substr($_GET['dni'], 0, 8))
    对应行代码替换为:
} else if (strlen($_GET['dni'])!==9 || !is_numeric(substr(($_GET['dni']), 0, 8))) {

完整修正后代码

<html>
    <head>
        <title>lapuente_de la pena_blanca_ModuloDWES_TareaEvaluativa02.php</title>
    </head>
    <body>
        <?php
        if (isset($_GET['enviar'])) {

            if (isset($_GET['fechaalquiler']) && ($_GET['fechaalquiler']!==null) && ($_GET['fechaalquiler']!=='')) {
                echo "Fecha de vuelta: ".gmdate('Y-m-d', strtotime($_GET['fechaalquiler']."+ 10 days"))."<br/>";
            } else {echo "Fecha no introducida <br/>";}

            if (isset($_GET['dni']) && ($_GET['dni']!==null) && ($_GET['dni']!=='')) {
                // 提前校验长度和数字合法性,优化判断逻辑
                if (strlen($_GET['dni'])!==9 || !is_numeric(substr($_GET['dni'], 0, 8))) {
                    echo "DNI incorrecto";
                } else if (substr("TRWAGMYFPDXBNJZSQVHLCKEO", (int)(substr($_GET['dni'], 0, 8)) % 23, 1) == substr($_GET['dni'], 8, 1)) {
                    echo "DNI correcto";
                } else {
                    echo "DNI incorrecto; la letra correcta sería ".substr("TRWAGMYFPDXBNJZSQVHLCKEO", (int)(substr(($_GET['dni']), 0, 8)) % 23, 1);
                }
            } else {
                echo "DNI no introducido";
            }
            
        }?>
             <form name="input" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">

                <label for="Fecha alquiler">Fecha alquiler</label>
                <input name="fechaalquiler" type="date">
                <?php echo "<br/>"?>

                <label for="DNI">DNI</label>
                <input name="dni" type="text">
                <br />

                <input type="submit" value="Enviar" name="enviar"/>            
             </form>
    </body>
</html>

额外优化说明:原代码DNI判断逻辑顺序不合理,会出现未校验长度就先截取字符计算字母的问题,修正后调整了判断顺序,避免异常报错。

内容的提问来源于stack exchange,提问作者Lordpascal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:15:04