到目前为止,我能想到的唯一数学方法是:
var age = 18
var today = new Date();
var myDate = new Date();
myDate.setFullYear(2013,3,13); /* My birthday is april 13th */
var y = (today - myDate);
var days = ( y / (1000*60*60*24));
if(days >= 360){
var age = age +1;
}
if(days >= 720){
var age = age +1;
}
//etc......
document.write(age);
有更好的方法来执行 if 语句吗?所以我不必每年写一个?我想不到!
答案 0 :(得分:2)
首先,你可以轻松地完成你的日子戏法:
age += Math.floor(days/360); // should be 365 imho
其次,您不需要将转换为年份的日期(由于闰年而在边缘处被破坏),但您可以使用getYear方法:
var age = 18
var today = new Date();
var myDate=new Date();
myDate.setFullYear(2013,3,13); /* My birthday is april 13th */
var age += today.getYear() - myDate.getYear();
// adjust for months and days
if (today.getMonth() < myDate.getMonth() ||
today.getMonth() == myDate.getMonth() && today.getDay() < myDate.getDay())
age--;
document.write(age);
答案 1 :(得分:1)
您可以尝试这样: -
var age = 18
var today = new Date();
var myDate=new Date();
myDate.setFullYear(2013,3,13); /* My birthday is april 13th */
var y = (today - myDate);
var days = ( y / (1000*60*60*24));
var x= Math.floor(days/365.25);
var age = age +x;
document.write( age);
答案 2 :(得分:0)
除非您想编写可以处理闰年,闰年和闰秒的算法,否则我建议使用Date类和/或库的内置方法来帮助您确定一年是否有365或366天。大多数年份都没有360天。