如何计算用户的年龄,具体取决于在文本框中输入的日期?
我希望能够计算YYYY / MM / DD的确切年龄,到目前为止我只能按年计算。
到目前为止我尝试过的代码:
function OnClick() {
var txtDate = $("#txtDate").val();
var date1 = new Date();
date1.setFullYear(txtDate);
var d1 = date1.getFullYear();
var date2 = new Date();
var d2 = date2.getFullYear();
var age = d2 - d1;
document.getElementById("Diven").innerHTML = age;
}
有什么想法吗?
答案 0 :(得分:3)
使用以下设置日期:new Date(birthYear, birthMonth, birthDay);
时,您需要从月份中减去1
。月份从00
计算。
例如,
var testDate = new Date(1988,10,12) is Sat Nov 12 1988 00:00:00
您可以尝试这种替代方式:
var today = new Date();
var inputBirthDate= new Date(birthYear, birthMonth - 1, birthDay);
var age = today.getFullYear() - inputBirthDate.getFullYear();
var month = today.getMonth() - inputBirthDate.getMonth();
if (month < 0 || (month === 0 && today.getDate() < inputBirthDate.getDate())) {
age--;
}
console.log(age);
这将根据输入的出生日期返回正确的年龄。
答案 1 :(得分:0)
因为我无法发表评论,所以我会在这里做。
我要做的第一件事是在js
中使用每个日期相关事物的momentjs如果我明白你的权利,你想要这样的东西吗?
How to get difference between 2 Dates in Years, Months and days using moment.js
答案 2 :(得分:0)
您可以使用Math.floor
和模运算符%
进行整数除法:
function CalculateAge() {
var dob1 = $("#txtBirthday").val();
var age1 = document.getElementById("#age");
var dateAry = dob1.value.split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var birthDate = new Date(birthYear, birthMonth, birthDay);
var currentDate = new Date();
var age = currentDate - birthDate; // don't forget the var keyword
var days = Math.floor(age / 86400000); // no need to use a string
var years = Math.floor(days / 365); // quite inaccurate actually
var remaning_days = days % 365; // use modulo operator
age1.value = years; // no need to type-cast
}
答案 3 :(得分:-1)
function CalculateAge() {
var dob1 = $("#txtBirthday");
var age1 = $("#age");
var dateAry = dob1.val().split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var one_day=1000*60*60*24;
var date1 = new Date(birthYear, birthMonth, birthDay);
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2 = new Date();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
var t = difference_ms/one_day;
age1.val(t/365);
}
如果你想要大约一年,请在结果中使用Math.random