When you use the getMonth
method, you receive a number because it returns the index of the month as an integer value. Keep in mind that January is represented as 0 and December as 11. If you need more information, check out the documentation for the getMonth
function.
To calculate a Date object that is 3 months prior to the current date, utilize the built-in Date method setMonth
.
function monthsBackFrom(date: Date, n: number): Date {
// Make a new date instead of modifying the original
const result = new Date(date);
// Be cautious, setMonth changes the date in place
result.setMonth(result.getMonth() - n); // Set to n months back
return result;
}
const now = new Date();
const threeMonthsBack: Date = monthsBackFrom(now, 3);
console.log(now.toString()) // Current date and time
console.log(threeMonthsBack.toString()); // Date three months ago, same time
Remember that setMonth
alters your date directly. It does not create a new one. Consider creating a new Date object when setting fromDate so that your toDate remains unaffected.
setMonth
can take negative values and numbers exceeding 12. Setting the month to -1
will adjust the date to December of the preceding year. On the other hand, setting the month to 12 will change the date to January of the following year*. The day and time details remain unchanged.