Given a Date or current date, and the task is to get the date three months prior using JavaScript.
Approach:
- First, select the date object.
- Then use the getMonth() method to get the months.
- Then subtract three months from the getMonth() method and set it using setMonth() method.
Example 1: This example uses getMonth() and setMonth() methods to get and set the month date.
Javascript
let d = new Date();console.log("Today's Date: " + d.toLocaleDateString());d.setMonth(d.getMonth() - 3);console.log("3 months Prior Date: " + d.toLocaleDateString()); |
Today's Date: 6/12/2023 3 months Prior Date: 3/12/2023
Example 2: This example uses getMonth() and setMonth() methods to get and set the month date as provided.
Javascript
let d = new Date("2010/12/02");console.log("Date: " + d.toLocaleDateString());d.setMonth(d.getMonth() - 3);console.log("3 Months Prior Date: " + d.toLocaleDateString()); |
Date: 12/2/2010 3 Months Prior Date: 9/2/2010
