从输入和输出中计算出一个人的年龄日期对象

时间:2012-03-20 13:32:56

标签: javascript date

在用户输入他们的出生信息后,我想将他们的年龄转换为毫秒,然后从当前日期减去它以返回他们的年龄,我该如何正确地做到这一点?:

var birthYear = parseInt(prompt ('Enter your birth year:'));
var birthMonth = prompt ('Enter the name of the month of birth:');
var birthDay = parseInt(prompt ('Enter your day of birth as an integer:'));
var milliDay = 1000*60*60*24; //Milliseconds in a day
monthAbb = 'janfebmaraprmayjunjulaugsepoctnovdec';
chineseZod = 12;
zodCycle = 1924; //Chinese Zodiac Cycle
var monthArr = new Array(11);


monthArr [0] = "jan";
monthArr [1] = "feb";
monthArr [2] = "mar";
monthArr [3] = "apr";
monthArr [4] = "may";
monthArr [5] = "jun";
monthArr [6] = "jul";
monthArr [7] = "aug";
monthArr [8] = "sep";
monthArr [9] = "oct";
monthArr [10] = "nov";
monthArr [11] = "dec";

var monthNum = monthAbb.indexOf(birthMonth.slice(0, 3).toLowerCase()) / 3; 
alert(monthNum);
var d = new Date (birthYear, monthNum, birthDay);
alert(d);

3 个答案:

答案 0 :(得分:0)

var today=new Date();
var millisec=today.getTime();
alert(millisec);

这将以毫秒为单位返回您的时间 例如,计算年龄: -

    var dt1 = new Date();
    var age = (dt1.getTime() - d.getTime()) / (60 * 60 * 24 * 1000);

答案 1 :(得分:0)

var d0 = new Date(2012, 0, 1); // 1 January 2012
var d1 = new Date(2012, 2, 31); // 31 March 2012

alert(d1 - d0); // 7776000000 which is the difference in milliseconds

上述情况可能会受到夏令时变化的影响。为避免这种情况,请使用UTC:

var d0 = Date.UTC(2012, 0, 1); // 1 January 2012
var d1 = Date.UTC(2012, 2, 31); // 31 March 2012

alert(d1 - d0); // 7776000000 which is the difference in milliseconds

答案 2 :(得分:0)

如果你想要一个十八岁的孩子等到2或3天的差异直到他的实际生日,那么闰年需要计算在内。

您可以将一年估计为 365.25 * 24 * 60 * 60 * 1000,并且通常是正确的。

function agefromYMD(y, m, d){
    var years, months, days, dA, nA,
    dob= new Date(y, m-1, d),
    now= new Date();
    now.setHours(0, 0, 0, 0);
    return Math.floor((now-dob)/(365.25*24*60*60*1000));
}

或者您可以查看日期,月份和完整年份。

function agefromYMD(y, m, d){
    var years, months, days, dA, nA,
    dob= new Date(y, m-1, d),
    now= new Date();
    now.setHours(0, 0, 0, 0);
    dA= [dob.getUTCFullYear(), dob.getUTCMonth(), dob.getUTCDate()];
    nA= [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()];
    years= nA[0]-dA[0];
    months= nA[1]-dA[1];
    days= nA[2]-dA[2];
    if(months<=0 && days<0)--months;
    if(months<0)--years;
    return years;
}

agefromYMD(1984,2,26)