Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  64] [ 4]  / answers: 1 / hits: 35663  / 15 Years ago, fri, october 30, 2009, 12:00:00

How can I create a date object which is less than n number of months from another date object? I am looking for something like DateAdd().



Example:



var objCurrentDate = new Date();


Now using objCurrentDate, how can I create a Date object having a date which is six months older than today's date / objCurrentDate?


More From » date

 Answers
54

You can implement very easily an addMonths function:



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


EDIT: As reported by @Brien, there were several problems with the above approach. It wasn't handling correctly the dates where, for example, the original day in the input date is higher than the number of days in the target month.



Another thing I disliked is that the function was mutating the input Date object.



Here's a better implementation handling the edge cases of the end of months and this one doesn't cause any side-effects in the input date supplied:





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




[#98416] Tuesday, October 27, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidan

Total Points: 72
Total Questions: 95
Total Answers: 121

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
aidan questions
Mon, Oct 11, 21, 00:00, 3 Years ago
Wed, Sep 29, 21, 00:00, 3 Years ago
Sun, Sep 5, 21, 00:00, 3 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;