有没有办法计算 Javascript 中两个不同日期之间的年数(也考虑闰年)和月份数?
这是我知道的获得年和月的最佳方法:
// Assumes Date From (df) and Date To (dt) are valid etc...
var df= new Date("01/15/2010");
var dt = new Date("02/01/2012");
var allMonths= dt.getMonth() - df.getMonth() + (12 * (dt.getFullYear() - df.getFullYear()));
var allYears= dt.getFullYear() - df.getFullYear();
var partialMonths = dt.getMonth() - df.getMonth();
if (partialMonths < 0) {
allYears--;
partialMonths = partialMonths + 12;
}
var total = allYears + " years and " + partialMonths + " months between the dates.";
var totalMonths = "A total of " + allMonths + " between the dates.";
console.log(total);
console.log(totalMonths);
return {jaren: allYears, maanden: partialMonths};
这可能是一个有用的来源:
以下代码片段包含我的解决方案。它基于这样的想法:当前日期 - 过去日期已经是结果。
如果你不想要负结果,你必须检查年和月不小于0。
const pastDate = '1989-02-10'
const period = new Date(new Date().getTime() - new Date(pastDate).getTime())
const years = period.getFullYear() - 1970 // at 1970 the date calendar starts
const months = period.getMonth()
console.log('years: ', years, ', month: ', months)
let olddate = "2023-01-09T00:00:00";
let newdata = "2024-05-09T00:00:00";
let castOldDate = new Date(olddate);
let castReportDate = new Date(newdata);
let howmanyYeas = (castReportDate.getFullYear() - castOldDate.getFullYear());
let howmanyMonth = Math.abs((castReportDate.getMonth() - castOldDate.getMonth()))
console.log( 'years: ' + howmanyYeas )
console.log( 'months: ' +howmanyYeas + howmanyMonth)
年:1 月数:14
您将在此处找到完整的 javascript 函数,并进行验证。
编辑:链接已失效 - 这是一个简单的 JS 行,用于计算两个日期之间的月份差异:
return dateTo.getMonth() - dateFrom.getMonth() +
(12 * (dateTo.getFullYear() - dateFrom.getFullYear()));
假设您有两个名为
dateTo
和 dateFrom
的变量中的日期。