在JavaScript中,如何计算两个Date()对象之间的差异,并仅返回差异的月数?
任何帮助都将是极好的 :)
在JavaScript中,如何计算两个Date()对象之间的差异,并仅返回差异的月数?
任何帮助都将是极好的 :)
“相隔月份数”的定义存在很多解释。:-)
您可以从JavaScript日期对象中获取年、月和日。根据您需要的信息,可以使用这些信息来计算两个时间点之间相差的月数。
例如,粗略地说:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
function test(d1, d2) {
var diff = monthDiff(d1, d2);
console.log(
d1.toISOString().substring(0, 10),
"to",
d2.toISOString().substring(0, 10),
":",
diff
);
}
test(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 16
test(
new Date(2010, 0, 1), // January 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 2
test(
new Date(2010, 1, 1), // February 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 1
注意:上面曾经有一个+ 1
,在这里:
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
// −−−−−−−−−−−−−−−−−−−−^^^^
months += d2.getMonth();
这是因为我原本说:
...这将查找两个日期之间有多少个“完整月份”,不包括部分月份(例如,不包括每个日期所在的月份)。
我删除它有两个原因:
不包括部分月份实际上并不是很多人(大多数人?)来到答案时想要的,所以我认为应该将它们分开。
即使按照这个定义,它也不能始终正常工作。:-D(抱歉。)
+1
”的问题,只需将一天添加到d2日期即可(对于我的情况起作用)。 - Renato Aloiif (d2.getDate() >= d1.getDate()) months++;
这样的内容是否有意义呢?因为如果你想要获取两个日期之间的月份差异,那么你是在日期前面还是后面会有所不同。 - velopreturn Math.abs(months);
我的意思是,它被命名为monthDiff,当结束日期作为第一个参数给出时,也应该执行相同的工作。 - Sercan Samet Savranfunction monthDiff(dateFrom, dateTo) {
return dateTo.getMonth() - dateFrom.getMonth() +
(12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}
//examples
console.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1
console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full year
console.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1
请注意月份索引是从0开始的。这意味着一月 = 0
,十二月 = 11
。roundUpFractionalMonths
参数设置为true
来防止这种情况,因此3个月零1天的差异将返回4个月。上面接受的答案(T.J. Crowder的答案)不准确,有时会返回错误的值。
例如,monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015'))
返回0
,显然是错误的。正确的差异要么是1个完整的月份,要么是向上舍入的2个月。
function getMonthsBetween(date1,date2,roundUpFractionalMonths)
{
//Months will be calculated between start and end dates.
//Make sure start date is less than end date.
//But remember if the difference should be negative.
var startDate=date1;
var endDate=date2;
var inverse=false;
if(date1>date2)
{
startDate=date2;
endDate=date1;
inverse=true;
}
//Calculate the differences between the start and end dates
var yearsDifference=endDate.getFullYear()-startDate.getFullYear();
var monthsDifference=endDate.getMonth()-startDate.getMonth();
var daysDifference=endDate.getDate()-startDate.getDate();
var monthCorrection=0;
//If roundUpFractionalMonths is true, check if an extra month needs to be added from rounding up.
//The difference is done by ceiling (round up), e.g. 3 months and 1 day will be 4 months.
if(roundUpFractionalMonths===true && daysDifference>0)
{
monthCorrection=1;
}
//If the day difference between the 2 months is negative, the last month is not a whole month.
else if(roundUpFractionalMonths!==true && daysDifference<0)
{
monthCorrection=-1;
}
return (inverse?-1:1)*(yearsDifference*12+monthsDifference+monthCorrection);
};
var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
month1++;
month2++;
}
var numberOfMonths;
1.如果您只想知道两个日期之间的月数,但不包括月份1和月份2
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;
2. 如果您想包含任何一个月份
numberOfMonths = (year2 - year1) * 12 + (month2 - month1);
3.如果您想同时包含这两个月份
numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;
numberOfMonths=(year2-year1)*12+(month2-month1)+1;
,它做的事情相同,但在语义上更加正确。 - Natim如果你需要计算完整的月份,而不管这个月是28、29、30还是31天。以下代码应该适用。
var months = to.getMonth() - from.getMonth()
+ (12 * (to.getFullYear() - from.getFullYear()));
if(to.getDate() < from.getDate()){
months--;
}
return months;
这是https://dev59.com/JXE85IYBdhLWcg3w8IXK#4312956答案的扩展版本,修复了从1月31日到2月1日(1天)计算1个月的情况。
它将涵盖以下内容:
start_date = new Date(year, month, day); //Create start date object by passing appropiate argument
end_date = new Date(new Date(year, month, day)
起始日期和结束日期之间的总月数:
total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth())
函数
返回月份之间的整数或数字差异。参数
传递是容错的。这意味着,函数仍将返回相同的值。
const diffInMonths = (end, start) => {
var timeDiff = Math.abs(end.getTime() - start.getTime());
return Math.round(timeDiff / (2e3 * 3600 * 365.25));
}
const result = diffInMonths(new Date(2015, 3, 28), new Date(2010, 1, 25));
// shows month difference as integer/number
console.log(result);
我知道这有点晚了,但还是想发布一下,以防对其他人有所帮助。这是一个我想出来的函数,似乎很好地计算了两个日期之间的月份差异。它比Mr.Crowder的函数更为严谨,通过遍历日期对象提供了更准确的结果。它是用AS3编写的,但你只需要去掉强类型即可得到JS版本。欢迎任何人将其改进得更漂亮!
function countMonths ( startDate:Date, endDate:Date ):int
{
var stepDate:Date = new Date;
stepDate.time = startDate.time;
var monthCount:int;
while( stepDate.time <= endDate.time ) {
stepDate.month += 1;
monthCount += 1;
}
if ( stepDate != endDate ) {
monthCount -= 1;
}
return monthCount;
}
将每个日期转化为月份计算,然后相减以求得差值。
var past_date = new Date('11/1/2014');
var current_date = new Date();
var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());
这将为您获取两个日期之间的月份差异,忽略天数。
为了进一步解释@T.J.的答案,如果你只是想要简单的月份而不是完整的日历月份,那么你可以检查d2的日期是否大于或等于d1的日期。也就是说,如果d2在其月份比d1在其月份晚,那么就会多出一个月。所以你应该可以这样做:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
// edit: increment months if d2 comes later in its month than d1 in its month
if (d2.getDate() >= d1.getDate())
months++
// end edit
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10
这并没有完全解决时间问题(例如3月3日下午4:00和4月3日下午3:00),但它更加准确,且只需编写几行代码。