Javascript - 根据用户的表单输入计算用户的年龄

时间:2015-01-14 11:42:17

标签: javascript

当用户以DDMMYYYY的形式输入他们的出生日期时,我该如何获取并将其转换为年份以告诉他们他们的年龄?

1 个答案:

答案 0 :(得分:2)

您需要使用Date对象来获取年龄:



var dateOfBirth = new Date(2010, 6, 17);
var today = new Date();

var diff = new Date(today.getTime() - dateOfBirth.getTime());

alert("Age: " + Number(diff.getUTCFullYear() - 1970) + " years, " + diff.getUTCMonth() + " months, " + Number(diff.getUTCDate() - 1) + " days");




读取:Date | MDN