如何使用moment.js在两个日期之间获得年,月和日

时间:2016-02-26 06:49:30

标签: angularjs

var oldDate =  moment('Tue May 20 2008 00:00:00 GMT+0530 (IST)');
var now = new moment();
var years = now.diff(oldDate,'years');

在控制台上我只有几年的时间。但我想要几个月的时间(7年9月7日7天?任何帮助

1 个答案:

答案 0 :(得分:1)

这样的东西?

// gets a human formatted date difference string: "X years, Y months, Z days"
function momentDiff(oldDate, newDate) {
  var oldDateMoment, newDateMoment, numYears, numMonths, numDays;

  oldDateMoment = moment(oldDate);
  newDateMoment = moment(newDate);

  numYears = newDateMoment.diff(oldDateMoment, 'years');
  oldDateMoment = oldDateMoment.add(numYears, 'years');
  numMonths = newDateMoment.diff(oldDateMoment, 'months');
  oldDateMoment = oldDateMoment.add(numMonths, 'months');
  numDays = newDateMoment.diff(oldDateMoment, 'days');

  return numYears + " years, " + numMonths + " months, " + numDays + " days.";
}

document.addEventListener('DOMContentLoaded', function() {
  var getDiffButton = document.querySelector('#getDiff');

  getDiffButton.addEventListener('click', function() {
    var oldDate = document.querySelector('#oldDate').value;
    var newDate = document.querySelector('#newDate').value;

    var answerDiv = document.querySelector('#answer');
    // call the function with two dates
    answerDiv.innerHTML = momentDiff(oldDate, newDate);
  });
});
<script src="http://momentjs.com/downloads/moment.js"></script>
<label for="oldDate">Old Date</label>
<input type="date" id="oldDate" name="oldDate" />
<br/>
<label for="newDate">New Date</label>
<input type="date" id="newDate" name="newDate" />
<br/>
<button id="getDiff">Get Diff</button>
<br/>
<div id="answer"></div>