如何从另一个日期对象创建一个小于n个月的日期对象?我正在寻找类似 DateAdd()
的东西。
示例:
var objCurrentDate = new Date();
现在使用 objCurrentDate
,我如何创建一个 Date
对象,其日期比今天的日期/objCurrentDate
早六个月?
最佳答案
您可以非常轻松地实现“addMonths” 函数:
function addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
addMonths(new Date(), -6); // six months before now
// Thu Apr 30 2009 01:22:46 GMT-0600
addMonths(new Date(), -12); // a year before now
// Thu Oct 30 2008 01:20:22 GMT-0600
编辑 据@Brien 报道,上述方法存在几个问题。它没有正确处理日期,例如,输入日期中的原始日期大于目标月份中的天数。
我不喜欢的另一件事是该函数正在改变输入的 Date 对象。
这里有一个更好的实现来处理月末的边缘情况,并且不会对提供的输入日期造成任何副作用:
const getDaysInMonth = (year, month) => new Date(year, month, 0).getDate()
const addMonths = (input, months) => {
const date = new Date(input)
date.setDate(1)
date.setMonth(date.getMonth() + months)
date.setDate(Math.min(input.getDate(), getDaysInMonth(date.getFullYear(), date.getMonth()+1)))
return date
}
console.log(addMonths(new Date('2020-01-31T00:00:00'), -6))
// "2019-07-31T06:00:00.000Z"
console.log(addMonths(new Date('2020-01-31T00:00:00'), 1))
// "2020-02-29T06:00:00.000Z"
console.log(addMonths(new Date('2020-05-31T00:00:00'), -6))
// "2019-11-30T06:00:00.000Z"
console.log(addMonths(new Date('2020-02-29T00:00:00'), -12))
// "2019-02-28T06:00:00.000Z"
关于javascript - 从另一个日期对象获取一个日期对象(六个月前),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1648392/