javascript 计算两个日期之间的月数,每个月迭代一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23460241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calculate the number of months between two dates, iterate a function on each month
提问by Tabaker78
I'm needing to write a function that takes two dates (startDate, endDate) calculates the time between them in months or years (depending on an input). When the number of months or years is found, I need to iterate a loop that runs a very simple ajax call (I'm adding a record to Quickbase) for every month OR year between the start and end dates.
我需要编写一个函数,它需要两个日期(startDate、endDate)来计算它们之间的时间(以月或年为单位)(取决于输入)。当找到月数或年数时,我需要迭代一个循环,该循环在开始日期和结束日期之间的每个月或年运行一个非常简单的 ajax 调用(我正在向 Quickbase 添加一条记录)。
I've taken a couple of hacks at this but I'm running into trouble when I try to calculate months (due to the calendar dates (i.e. feb having 28 days etc)... I've calculated the time between the two dates in days, but I need months or years.
我已经采取了一些技巧,但是当我尝试计算月份时遇到了麻烦(由于日历日期(即 2 月有 28 天等)......我已经计算了两个日期之间的时间在几天内,但我需要几个月或几年。
Any help would be appreciated!
任何帮助,将不胜感激!
回答by Sajad Karuthedath
just to start try
刚开始尝试
function Noofmonths(date1, date2) {
var Nomonths;
Nomonths= (date2.getFullYear() - date1.getFullYear()) * 12;
Nomonths-= date1.getMonth() + 1;
Nomonths+= date2.getMonth() +1; // we should add + 1 to get correct month number
return Nomonths <= 0 ? 0 : Nomonths;
}
回答by SDMulroy
obtain date1 year and date2 year. get the difference and multiply by 12. obtain date1 month and date2 month. get the difference. add the differences together.
获取 date1 year 和 date2 year。得到差值并乘以 12。得到 date1 月和 date2 月。得到差异。将差异加在一起。