查找特定日期之后的月份

时间:2016-08-19 14:29:25

标签: javascript node.js

我能够找到两个月之间的差异,但我确切的要求是从特定日期过去了几个月。

假设用户在2016年7月2日或2016年7月31日注册,那么8月1日它应该返回 - 第二个月,即7月和8月。 如果用户在2016年8月2日和今天是2016年8月18日注册,它应该返回给我。

请注意,我们还要考虑年份数,即年度变化应该算得上13,14等。

我已经尝试了很多方法来找出它全部失败

1 个答案:

答案 0 :(得分:0)

这应该足够了:

date2.getMonth() - date1.getMonth() + (date2.getYear() - date1.getYear())*12 + 1

示例:

var date1= new Date("2016-07-02");
var date2= new Date("2016-08-01");
console.log(date2.getMonth() - date1.getMonth() + (date2.getYear() - date1.getYear())*12 + 1);
> 2

var date1= new Date("2016-08-02");
var date2= new Date("2016-08-18");
console.log(date2.getMonth() - date1.getMonth() + (date2.getYear() - date1.getYear())*12 + 1);
> 1

var date1= new Date("2015-08-02");
var date2= new Date("2016-08-18");
console.log(date2.getMonth() - date1.getMonth() + (date2.getYear() - date1.getYear())*12 + 1);
> 13