代码之家  ›  专栏  ›  技术社区  ›  Tom Gullen

javascript月份差异

  •  11
  • Tom Gullen  · 技术社区  · 13 年前

    如何计算javascript中月份的差异?

    请注意,也有类似的问题,如: What's the best way to calculate date difference in Javascript

    但这些都是基于MS差异,当某些月份的天数与其他月份的天数不同时!

    有没有简单的方法来计算两个日期之间的月份差异?

    为了清楚起见,我需要知道日期的跨度,例如:

    Jan 29th 2010, and Feb 1st 2010 = 2 months
    Jan 1st 2010, and Jan 2nd 2010 = 1 month
    Feb 14th 2010, Feb 1st 2011 = 13 months
    Feb 1st 2010, March 30th 2011 = 14 months
    
    4 回复  |  直到 8 年前
        1
  •  20
  •   Tom Gullen    13 年前
    DisplayTo.getMonth() - DisplayFrom.getMonth() + (12 * (DisplayTo.getFullYear() - DisplayFrom.getFullYear())));
    

    GetMonth减去GetMonth将给出日期两个月之间的月份差异。

    然后,我们将12乘以年份差,并将其加到结果中,得到整个月的跨度。

        2
  •  5
  •   KooiInc    13 年前

    [ 编辑 ]根据评论,我认为是正确的。使用公认的答案,我会使用如下的方法:

    var  datefrom = new Date('2001/03/15')
        ,dateto = new Date('2011/07/21')
        ,nocando = datefrom<dateto ? null : 'datefrom > dateto!'
        ,diffM = nocando || 
                 dateto.getMonth() - datefrom.getMonth() 
                  + (12 * (dateto.getFullYear() - datefrom.getFullYear()))
        ,diffY = nocando || Math.floor(diffM/12)
        ,diffD = dateto.getDate()-datefrom.getDate()
        ,diffYM = nocando || 
                   (diffY>0 ? ' Year(s) ' : '')
                   + diffM%12+' Month(s) '+(diffD>0? (diffD+' day(s)') : '') ;
    
     console.log(diffYM); //=> 10 Year(s) 4 Month(s) 6 day(s)
    
        3
  •  3
  •   Marina    11 年前

    我在网站上找到了以下内容 http://ditio.net/2010/05/02/javascript-date-difference-calculation/ :

    inMonths: function(d1, d2) {
            var d1Y = d1.getFullYear();
            var d2Y = d2.getFullYear();
            var d1M = d1.getMonth();
            var d2M = d2.getMonth();
    
            return (d2M+12*d2Y)-(d1M+12*d1Y);
        }
    

    在您的情况下,由于您希望在日期范围内包括所有月份,所以我只需在上面的代码中添加1来修改它: return (d2M+12*d2Y)-(d1M+12*d1Y) + 1;

        4
  •  1
  •   shoaib fazlani    9 年前
    function calcualteMonthYr(){
        var fromDate =new Date($('#txtDurationFrom2').val()); // Date picker (text fields)
        var toDate = new Date($('#txtDurationTo2').val());
        var months=0;
            months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
            months -= fromDate.getMonth();
            months += toDate.getMonth();
                if (toDate.getDate() < fromDate.getDate()){
                    months--;
                }
        $('#txtTimePeriod2').val(months); // result
    }