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

在ASP.NET MVC中实现年龄的年与月共同显示功能

完善年龄计算器的月份计算功能

下面是修改后的完整代码,实现了年份+月份的年龄计算,输出格式符合“XX年XX个月”的要求:

Razor视图(HTML部分)

<html>
<body> 
    <div class="form-group row">
        <label class="control-label col-sm-2" asp-for="Dob">Birth date:</label>
        <div class="col-sm-5"> 
            <input asp-for="Dob" id="txtDOB" asp-format="{0:yyyy-MM-dd}" class="form-control" placeholder="YYYY-MM-DD" /> 
        </div>
    </div>

    <div class="form-group row">
        <label class="control-label col-sm-2" for="Age">Age:</label>
        <div class="col-sm-5">
            <input type="text" id="age" asp-for="Age" class="form-control" readonly />
        </div>
    </div>
</body>
</html> 

<script src="~/Scripts/jquery-3.4.1.min.js"></script>

注意:移除了重复引用的jquery-3.4.1.js,避免加载冲突;给年龄输入框添加readonly属性,防止用户手动修改。

JavaScript部分

$(document).ready(function () {
    $("#txtDOB").change(function () {
        var dob = $("#txtDOB").val();

        if (!dob) {
            $("#age").val("");
            return;
        }
        
        $("#age").val(getAge(dob));
    });

    function getAge(birthStr) {
        const birthDate = new Date(birthStr);
        const currentDate = new Date();

        let years = currentDate.getFullYear() - birthDate.getFullYear();
        let months = currentDate.getMonth() - birthDate.getMonth();
        const currentDay = currentDate.getDate();
        const birthDay = birthDate.getDate();

        // 处理日期不足的借位逻辑
        if (currentDay < birthDay) {
            months--;
            if (months < 0) {
                years--;
                months += 12;
            }
        }

        return `${years}年${months}个月`;
    }
});

关键逻辑说明

  1. 精准日期计算:摒弃原有的毫秒差间接计算方式,直接对比当前日期与生日的年、月、日数值,避免闰年、不同月份天数差异带来的误差。
  2. 借位处理:当当前日期的天数小于生日当天时,对月份进行减1操作;若月份变为负数,则从年份借1(年份减1,月份加12),确保年龄计算符合实际逻辑。
  3. 空值处理:出生日期输入框为空时,清空年龄输入框,优化用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:45:38