可以使用JavaScript中的Date对象来计算年龄,具体实现如下:
function getAge(birthDate) { const now = new Date(); const birth = new Date(birthDate); let age = now.getFullYear() - birth.getFullYear(); // 如果生日还未到,年龄减1 if (now.getMonth() < birth.getMonth() || (now.getMonth() === birth.getMonth() && now.getDate() < birth.getDate())) { age--; } return age; }
这个方法接收一个参数 birthDate
,即生日,使用 new Date(birthDate)
将其转换为Date对象,然后获取当前时间的年份和出生日期的年份之差,然后进行判断,如果当前月份小于出生月份,或者是当前月份等于出生月份,但是当前日期小于出生日期,年龄需要减一。
使用示例:
//生日为1995年3月12日 getAge('1995-03-12'); // 返回26