Categories
JavaScript Answers

How to Add Weeks to a Date Using JavaScript?

Spread the love

Sometimes, we want to add weeks to a date using JavaScript.

In this article, we’ll look at how to add weeks to a date using JavaScript.

Add Weeks to a Date Using JavaScript

To add weeks to a date using JavaScript, we can use the getDate method to get the date of the month.

Then we can add the number of weeks multiplied by 7 and pass that to setDate .

For instance, we write:

const numWeeks = 2;
const dt = new Date(2021, 1, 1);
dt.setDate(dt.getDate() + numWeeks * 7);
console.log(dt);

to add 2 weeks to Feb 1, 2021.

We call setDate with dt.getDate() + numWeeks * 7 add 14 days to the date returned by dt.getDate .

setDate will automatically calculate the correct date no matter how the dates are added.

Therefore dt is:

Mon Feb 15 2021 00:00:00 GMT-0800 (Pacific Standard Time)

according to the console log.

Conclusion

To add weeks to a date using JavaScript, we can use the getDate method to get the date of the month.

Then we can add the number of weeks multiplied by 7 and pass that to setDate .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *