计算年,月,日

时间:2016-05-23 20:25:37

标签: javascript jquery-mobile

我试图让这段代码计算年,月和日,但下面的代码总是计算一个月太多。

$(document).on("pagecreate","#pagethree", function(){ 
    $("#btnCalc").on("click", function(e){
        var born = $("#born").datebox('getTheDate');
        var death = $("#death").datebox('getTheDate');
        var age = death.getFullYear() - born.getFullYear();
        var m = death.getMonth() - born.getMonth();
        var da = death.getDate() - born.getDate();

        if (m < 0 || (m === 0 && death.getDate() < born.getDate())) {
            age--;
        }
        if(m<0){
            m +=12;
        }
        if(da<0){
            da +=30;
        }
        $("#p").popup("open");
        $('#altertext').html((age) + " Years "+ (Math.abs(m))+ " Months " + (Math.abs(da)) + " Days" );
    });
})

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

为什么不对天数进行计算?

$(document).on("pagecreate","#pagethree", function()
{ 
    $("#btnCalc").on("click", function(e)
    {
        var born = $("#born").datebox('getTheDate');
        var death = $("#death").datebox('getTheDate');

        // you can subtract two date objects to get the milliseconds in between
        // then figure out how many days that is
        // 1 day = 24 hours
        // 1 hour = 60 minutes
        // 1 minute = 60 seconds
        // 1 second = 1000 milliseconds
        var ageInDays = (death - born) / 1000 / 60 / 60 / 24;

        // days / 365 tells you years
        var years = Math.floor(ageInDays / 365);

        // the remainder tells you months
        var months = Math.floor(ageInDays % 365 / 31);

        // the remainder tells you days
        var days =  Math.floor(ageInDays % 365 % 31);

        $("#p").popup("open");
        $('#altertext').html(years + " Years " + months + " Months " + days + " Days" );
  });
})

当然,这并没有考虑到月份和年份的天数不同的事实。

如果你想要更精确的东西,那就像@ssube说并使用一个库。

**编辑**

这应该有效且准确

// calculate difference between two dates in years, months, days
function dateDiff(start, end)
{
    // set a new temp variable we're gonna modify
    var s = new Date(start.getTime());

    // how many years
    var years = end.getFullYear() - start.getFullYear();

    // add this many years to the temp var
    s.setFullYear(s.getFullYear() + years);

    // if we've passed the end then we need to go back one year
    if(s > end)
    {
        years--;
        s.setFullYear(s.getFullYear() - 1);
    }

    // how many months between the two
    var months = 12 - s.getMonth() + end.getMonth();

    // add this many months to the temp var
    s.setMonth(s.getMonth() + months);

    // if we've passed the end then we need to back one month
    if(s > end)
    {
        months--;
        s.setMonth(s.getMonth() - 1);
    }

    // now just calculate the days between the end and temp start
    var days = Math.floor((end - s) / 1000 / 60 / 60 / 24)

    return [years, months, days];
}

它基本上可以通过在开始之前加上几年甚至几个月直到我们结束。

答案 1 :(得分:0)

感谢您的回答!我刚刚在这个if语句中添加了m--:

if(da<0){
        da +=30;
        m--;
    }