How to Create a 3 Month Date Range in JavaScript?

Estimated read time 1 min read

To create a 3-month date range in JavaScript, you can use the Date object and some arithmetic to calculate the start and end dates.

Here’s an example of how you can do this:

const currentDate = new Date();

const startDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 2, 1);
const endDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);

console.log(startDate.toLocaleDateString());
console.log(endDate.toLocaleDateString());

In the above example, the currentDate variable is set to the current date using the Date object.

The startDate is set to the first day of the month that is 3 months ago. This is calculated by subtracting 2 from the current month and setting the day to 1.

The endDate is set to the last day of the next month. This is calculated by adding 1 to the current month and setting the day to 0, which returns the last day of the previous month.

Both the startDate and endDate are logged to the console using the toLocaleDateString() method, which formats the date as a string using the local date format.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply