The reason you are getting a number from getMonth
is because it returns the integer value, or "index", of a month. January is 0, December is 11. See the getMonth
docs for more details.
To get a new Date 3 months in the past, you should use the built in Date setMonth
function.
function monthsBackFrom(date: Date, n: number): Date {
// Create a new date so the original is not modified
const result = new Date(date);
// Careful, setMonth modifies the date object in place
result.setMonth(result.getMonth() - n); // Set to n months back from current
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 back, same time
Note that setMonth
modifies your date in place. It does not create a new one. You will most likely need to create a new Date object when setting fromDate so your toDate is not affected.
setMonth
also supports negatives and values greater than 12. Setting the month to -1
will set the date to December of the previous year. Setting the month to 12 will set the date to January of the next year*. Day and time information remains the same.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…