我将如何在JavaScript中获得两个月(YYYYMM)之间的差异?

我将如何在JavaScript中获得两个月(YYYYMM)之间的差异?,javascript,date,Javascript,Date,从这两个月开始,我将如何在JavaScript中获得两个月之间的差异 var frommonth="201912"; var tomonth="201810"; 不要解析yyyym。它认为 201912 >代码>年 因此,使用match()解析YYYYMM var from=“201912”; var to=“201810”; 功能分析月(str){ 返回str.match(/(\d{4})(\d{2})/).splice(1.map(编号) } var[fromY,fromM]=parse

从这两个月开始,我将如何在JavaScript中获得两个月之间的差异

var frommonth="201912";
var tomonth="201810";
不要解析
yyyym
。它认为<代码> 201912 >代码>年

因此,使用
match()
解析
YYYYMM

var from=“201912”;
var to=“201810”;
功能分析月(str){
返回str.match(/(\d{4})(\d{2})/).splice(1.map(编号)
}
var[fromY,fromM]=parseMonth(从)
变量[toY,toM]=月(至)
变量结果=(fromY-toY)*12+(fromM-toM)

console.log(结果“月”)
您可以将
frommonth
tomonth
作为参数传递给函数,并可以执行差异计算

此处
新日期(frommonth.子字符串(0,4),frommonth.子字符串(4,0)
表示

->
frommonth.substring(0,4)
=>从字符串中获取年份

->
frommonth.substring(4)
=>从字符串中获取月份

->
0
=>设置日期为0

明天的
也考虑到了这一点

Math.round(timeDiff/(2e3*3600*365.25))也考虑闰年……/P>

const frommonth=“201912”;
const tomonth=“201810”;
const diffInMonths=(结束,开始)=>{
var timeDiff=Math.abs(end.getTime()-start.getTime());
返回数学舍入(timeDiff/(2e3*3600*365.25));
}
const result=diffInMonths(新日期(从month.substring(0,4),从month.substring(4,0),新日期(从tomon.substring(0,4),到tomon.substring(4,0));
//月差

控制台日志(结果)请不要用java标记javascript问题。尽管名称“javascript”中有“java”,但这两种语言并不相同。他们甚至没有关系。这两次约会可能不是你需要的。你想指定什么日期?另外,您是否使用moment.js?(是的,您标记了它,但不在代码中使用它…)365.25不包含闰年。没有哪一年是一天四分之一的。365.25也是平均儒略年的长度。在现代公历中,平均长度为365.2425天。但是,任何一年都不会发生平均年份。(四舍五入仅在结果恰好符合您的偏好时才有帮助。如果差异足够大,四舍五入将产生错误的结果。)@MattJohnson Pint,我将其作为此答案的参考,并为闰年支持做了此更改。但由于我不太熟悉日期,timediff,我可能会有点错误。。很高兴向你了解这件事。。谢谢不需要转换成数字,减法也可以
var date1 = new Date(fromdate);
var date2 = new Date(todate);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 

var fromYear=date1.getFullYear();
var toYear=date2.getFullYear();
var diffyear =toYear-fromYear;