javascript获得两个日期之间的月份

时间:2017-03-22 17:09:26

标签: javascript date

我想要两个日期之间的月数。我在stackoverflow上看过很多帖子,但没有人是我的情况。 我想有这个解决方案:

From 2017-01-19 to 2017-01-23 = 1 Month
From 2017-01-19 to 2017-02-15 = 2 Months
From 2017-01-30 to 2017-02-28 = 2 Months
From 2017-01-19 to 2019-03-01 = 27 Months

我希望我很清楚

3 个答案:

答案 0 :(得分:2)

您的测试用例有点不清楚。顺便说一句,如果你想在几个月之间获得差异,那么你可以通过以下方式实现它。我假设您的日期为var d1 = "2017-01-19", d2 = "2017-01-23";然后您可以执行以下操作:

var date1 = d1.split("-");
var date2 = d2.split("-");
// assuming that you don't know which date comes first
// otherwise no need to use Math.abs()
var months = Math.abs(date2[0] - date1[0]) * 12 + Math.abs(date2[1] - date1[1]) + 1;

或者可以这样做:

//assuming a month of 30 days
var months = Math.floor(Math.abs(new Date(d1) - new Date(d2)))/(1000 * 60 * 60 *24 * 30) + 1;

答案 1 :(得分:2)

请使用这些代码来获得月差异

var date1=new Date(2017,1,19);//Remember, months are 0 based in JS
var date2=new Date(2017,4,19);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
  month1++;
  month2++;
}
var numberOfMonths=(year2 - year1) * 12 + (month2 - month1) - 1;
alert("Number of months "+numberOfMonths+1);

答案 2 :(得分:0)

假设1个月= 30天你可以做



var dates = [
  {from: '2017-01-19', to: '2017-02-23'},
  {from: '2017-01-19', to: '2017-02-15'},
  {from: '2017-01-30', to: '2017-02-28'},
  {from: '2017-01-19',to: '2019-03-01'}
];

dates.forEach(function(item) {
  var from = new Date(item.from);
  var to = new Date(item.to);
  var diffMonth = Math.round((to - from) / (1000 * 60 * 60 * 24 * 30));

  console.log(
    from.toJSON().split('T')[0],
    'to',
    to.toJSON().split('T')[0],
    diffMonth + ' month' + (diffMonth > 1 ? 's' : '')
  );
});