JavaScript 计算年龄:使用 Date 对象和后端返回的 DateTime 类型

本文将详细讲解如何利用 JavaScript 的 Date 对象和后端返回的 DateTime 数据计算年龄,提供完整代码示例和步骤解释。

后端代码

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. 返回计算出的年龄。

总结

本文介绍了如何使用 JavaScript 的 Date 对象和后端返回的 DateTime 数据计算年龄,希望对大家有所帮助。

JavaScript 计算年龄:使用 Date 对象和后端返回的 DateTime 类型

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

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