在两个日期之间获取不正确的月份差异

Getting incorrect month difference between 2 dates

我有 2 个日期如下:

Todays date = 2021-10-13 11:03:57.560

Old date = 2016-08-07 11:03:57.560

我想要与 todays date Month - Old date Month = 10 - 8 = 2

的月差

代码:

console.log(moment().diff($scope.creationTime, 'months')); // returns 62

预期: 当前月份 - 旧日期月份

谁能帮我解决这个问题?

现在你得到 62 因为这两个日期相隔 5 年零 2 个月:

5 * 12 + 2 = 62

消除年份差异的一种简单方法是使用余数运算符并执行 monthDifference % 12 这将只给出月数,而不管年份:

function monthDiff(date1, date2) {
  const monthDifference = moment(date1).diff(moment(date2),  'months');
  return monthDifference % 12;
}


console.log(monthDiff("2021-10-13 11:03:57.560", "2016-08-07 11:03:57.560"));
console.log(monthDiff("2021-10-07 11:03:57.560", "2016-08-13 11:03:57.560"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

使用 moment.js 中的 month() 得到月份和之后的简单数学:

const today = moment();
const someday = moment('2011-01-01 00:00Z');

console.log(today.month())
console.log(someday.month())

console.log(Math.abs(today.month()-someday.month()))

你不需要时间来做你也使用 Date

new Date().getMonth - to get your current month
new Date('2016-08-07 11:03:57.560').getMonth() - to get the month of your old date

console.log(new Date().getMonth() - new Date('2016-08-07 11:03:57.560').getMonth())