得到一个月的差异javascript

时间:2013-12-27 13:14:29

标签: javascript datediff

我希望在几个月和几年之间得出2个日期之间的差异。 问题是因为任何一个月都没有设定的天数,我无法弄清楚如何将2个日期与28到31天之间的月份进行比较。我已经做了几年和几个月,因为我知道有12个月到一年,所以我可以计算它。也许有人知道一种解决这个问题的方法。这是我到目前为止所拥有的。谢谢你的阅读。

var date1 = new Date(2013,10,1);
var date2 = new Date();

var y1 = date1.getFullYear();
var m1 = date1.getMonth();

var y2 = date2.getFullYear();
var m2 = date2.getMonth();

var totDiff = (y1 - y2) * 12 + (m1 - m2 -1);

var yDiff = Math.floor(Math.abs(totDiff) / 12);
var mDiff = totDiff - (Math.floor((totDiff) / 12) * 12);

console.log("years: " + yDiff + " months: " + mDiff);  

2 个答案:

答案 0 :(得分:1)

我会在'while'循环中迭代一个日期,增加较低的日期并计算实现更大日期所需的迭代次数。这样你就可以计算出任何时间单位的差异。

该方法可能如下所示。相当多的代码,但我希望它很清楚(参见下面的' dateDiff '方法):

function addTime(date, unit){
    var date = new Date(date);
    switch (unit){
        case "day":
            date.setDate(date.getDate() + 1);
            break;
        case "month":
            date.setMonth(date.getMonth() + 1);
        break;
        case "year":
            date.setYear(date.getFullYear() + 1);
        break;
    }
    return date;
}
function dateDiff(from, to){
    var from = new Date(from),
        to = new Date(to),
        res = {
            days:0,
            months:0,
            years:0
        };

    while(addTime(from, 'year').valueOf() <= to.valueOf()){
        res.years++;
        from = addTime(from, 'year');
    }
    while(addTime(from, 'month').valueOf() <= to.valueOf()){
        res.months++;
        from = addTime(from, 'month');
    }
    while(addTime(from, 'day').valueOf() <= to.valueOf()){
        res.days++;
        from = addTime(from, 'day');
    }
    return res;
}

和用法:

dateDiff(new Date(..some date..), new Date(..some greater date..))

实施例

console.log( dateDiff(new Date(2013, 11, 1), new Date()) );
//Object {days: 26, months: 0, years: 0} 

console.log( dateDiff(new Date(2000, 0, 1), new Date()) );
//Object {days: 26, months: 11, years: 13} 

答案 1 :(得分:0)

var today=new Date('January 01, 2014 00:00:00');
var tt=new Date();

var ss=(today-tt)/1000;
days = parseInt(ss / 86400);
   ss = ss % 86400;     
    hours = parseInt(ss / 3600);
    ss = ss % 3600;     
    minutes = parseInt(ss / 60);
    seconds = parseInt(ss % 60);
document.getElementById('d').innerHTML=days; 
document.getElementById('h').innerHTML=hours;
document.getElementById('m').innerHTML=minutes;
document.getElementById('s').innerHTML=seconds;

通过使用上面的一些计算,您可以找到两个日期之间的差异,包括年,日,小时。分钟甚至秒。