Moment.js - two dates difference in number of days

后端 未结 6 2116
不知归路
不知归路 2020-12-03 06:14

I get incorrect results when trying to find numeric difference between two dates:

var startDate = moment( $(\'[name=\"date-start\"]\').val(), \"DD.MM.YYYY\")         


        
6条回答
  •  醉梦人生
    2020-12-03 07:16

    From the moment.js docs: format('E') stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.

    From the moment.js docs again, here is what they suggest:

    var a = moment([2007, 0, 29]);
    var b = moment([2007, 0, 28]);
    a.diff(b, 'days') // 1
    

    Here is a JSFiddle for your particular case:

    $('#test').click(function() {
      var startDate = moment("13.04.2016", "DD.MM.YYYY");
      var endDate = moment("28.04.2016", "DD.MM.YYYY");
    
      var result = 'Diff: ' + endDate.diff(startDate, 'days');
    
      $('#result').html(result);
    });
    #test {
      width: 100px;
      height: 100px;
      background: #ffb;
      padding: 10px;
      border: 2px solid #999;
    }
    
    
    
    
    Click Me!!!

提交回复
热议问题