后端代码:

from datetime import datetime

def get_birthday():
    birthday = datetime(1995, 5, 10) # 假设生日为1995年5月10日
    return birthday

前端代码:

function getAge() {
    var birthday = new Date("1995-05-10"); // 假设生日为1995年5月10日
    var today = new Date();
    var age = today.getFullYear() - birthday.getFullYear();
    if (today.getMonth() < birthday.getMonth() || (today.getMonth() == birthday.getMonth() && today.getDate() < birthday.getDate())) {
        age--;
    }
    return age;
}

console.log(getAge()); // 输出 26(当前为2021年)

解释:

  1. 后端返回一个datetime类型的对象,我们假设它为birthday;
  2. 前端使用new Date()方法创建一个生日为1995年5月10日的Date对象;
  3. 使用getFullYear()方法获取当前年份和生日年份,相减得到年龄;
  4. 如果当前月份小于生日月份或者当前月份等于生日月份但是当前日期小于生日日期,说明还没有过生日,年龄需要减1;
  5. 返回计算出的年龄
net后端 返回一个datatim类型数据 前端怎么用当前的年月日相减得到一个 岁数 详细代码该如何实现

原文地址: http://www.cveoy.top/t/topic/fsLV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录