moment.js 如何计算某天 到 某天 经过了多少月, 分别是那几个月?

目前有个这样的需求就是用moment.js 能不能得到 某一天到某一天一共经过了几个月,那几个月?

比如: 2016-01-15 / 2016-07-31 通过计算能得到 这之间经过了 2016-01、2016-02、2016-03、2016-04、2016-05、2016-06、2016-07 这几个月

哪位大神能帮忙看看这个应该怎么写? moment里面貌似没有这样的功能? 没有moment的也没关系, 纯js/PHP/JAVA的都可以,都能看懂,谢谢了,急求!

阅读 9.5k
3 个回答

这样么?

修正一把:

再来修正一把

2020 年 再更(貌似是moment的api有变化,用最新版的moment已经无法正确计算了,随便更如下)

function diffMonths(date1, date2) {
    const a = moment(date1).startOf('month');
    const b = moment(date2).startOf('month');
    const diff = Math.abs(b.diff(a, 'months'));

    return Array.apply([], new Array(diff + 1)).map(function(item, index) {
        return a.clone().add(index, 'months').format('YYYY-MM');
    });
};



console.log(diffMonths([2016, 0, 15], [2016, 6, 31]));
console.log(diffMonths([2016, 6, 31], [2016, 7, 1]));
console.log(diffMonths([2016, 6, 1], [2016, 6, 31]));
console.log(diffMonths([2016, 6, 31], [2016, 8, 1]));
console.log(diffMonths([2016, 6, 31], [2017, 8, 1]));
console.log(diffMonths([2016, 6, 31], [2017, 0, 1]));
我看了你最后一次提供的做法,光比较月份的话,最后两个case是跑不通的,所以才想到再改一次。万没想到,这么个小东西也确实写了好久

看到你的帖子很有启发, 自己写了一个.

/**
 * Calcaulate diff Months between two month
 *
 * @Author   Hosea
 * @DateTime 2017-08-16T14:56:41+0800
 * @param    {Monment} StartDate
 * @param    {Monment} EndDate
 * @return   {Array} month array
 */
function calDiffMonths(StartDate, EndDate) {
  let CurrentMonth = StartDate.startOf('month');
  let Months = [];
  while (CurrentMonth <= EndDate) {
    Months.push(CurrentMonth.clone());
    CurrentMonth = CurrentMonth.add(1, 'months');
  }
  return Months;
}
新手上路,请多包涵

用了上面的方法是这样的,为什么?
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题