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

如何用getFullYear()从<input type="date"/>获取年份?计算年龄报错求助

解决"Uncaught TypeError: birthDate.value.getFullYear is not a function"错误

错误原因

<input type="date">的value属性返回的是ISO 8601格式的字符串(比如"1995-10-25"),不是Date对象,直接调用getFullYear()方法自然会触发类型错误。

修正方案

把输入的日期字符串转换成Date对象后再调用日期方法,同时建议补充生日校验逻辑(避免未到生日就多算一岁的情况):

修正后的JavaScript代码

function checkAge(){
    // 获取输入框元素
    let birthDateInput = document.getElementById("dateOfBirth");
    
    // 先判断用户是否选择了日期
    if (!birthDateInput.value) {
        alert("请先选择出生日期");
        return;
    }
    
    // 将日期字符串转为Date对象
    let birthDate = new Date(birthDateInput.value);
    let today = new Date();
    
    // 计算年份差
    let userAge = today.getFullYear() - birthDate.getFullYear();
    
    // 校验月份和日期,修正未到生日的情况
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        userAge--;
    }
    
    // 这里可以处理年龄结果,比如显示到页面
    console.log("你的年龄是:", userAge);
}

对应的HTML代码

<label for="dateOfBirth">Date of Birth<strong>*</strong></label>
<input type="date" id="dateOfBirth" name="D.O.B" >
<!-- 添加触发计算的按钮 -->
<button onclick="checkAge()">计算年龄</button>

额外提示

  • 空值判断很重要,避免用户未选日期时new Date("")生成无效日期(Invalid Date),导致后续计算出错。
  • 主流浏览器对<input type="date">兼容性较好,浏览器本身会做基础的日期格式校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:25:22