How to Add Weeks To A Date Using JavaScript

Don’t worry if you’re having trouble adding weeks to a date in JavaScript. This article will share solutions to add weeks to a date using JavaScript. Let’s get started.

How to add weeks to a date using JavaScript

Let’s say we have a date object. What we have to do now is add a few weeks to this object. The following example briefly describes how we add weeks to a date using JavaScript.

Example:

const date = new Date("Dec 25, 2022");

// Add 3 weeks to date object
date.setDate(date.getDate() + 3 * 7);

console.log(date.toDateString());

Output:

Sun Jan 15 2023

First, we use the getDate() method to get the day of the month (1 to 31) of the date object. We then use the setDate() method to add the number of days corresponding to the number of weeks we will add to this date object.

The setDate() method takes all integer values as input. If the number of days in the previous month is exceeded (30 or 31), the month will automatically increment; for example, 51 is the 20th day of the following month (if it is 31 days). If the input is a negative number, then the month is decremented; for example, -1 is the last day of the previous month.

We create a reusable function of this solution, and the full code is as follows:

Example:

function addWeek(date, weeks) {
    // Add weeks to a date
    date.setDate(date.getDate() + weeks * 7);
    return date;
}

// Create a date object
const date = new Date("Dec 25, 2022");

// Add 3 weeks to date object
console.log(addWeek(date, 3).toDateString());

Output:

Sun Jan 15 2023

However, the setDate() method will change the original date object. You will often want to keep your date object the same. The solution is to clone your object and add the week to the copy of the original date object.

We will call the getTime() method on the original date object. The getTime() method returns an integer representing the number of milliseconds since January 1, 1970, 00:00:00.

We then create a new date object from the result returned by the getTime() method plus the number of milliseconds corresponding to the number of weeks to be added to the original date.

Example:

function addWeek(date, weeks) {
    // Number of milliseconds of weeks
    const msWeek = weeks * 1000 * 60 * 60 * 24 * 7;

    // Add weeks to a date
    const newDate = new Date(date.getTime() + msWeek);

    return newDate;
}

// Create a date object
const date = new Date("Dec 25, 2022");

// Add 3 weeks to date object
console.log(addWeek(date, 3).toDateString());

Output:

Sun Jan 15 2023

Read more about the JavaScript Date methods here.

Summary

We have shared two solutions to add weeks to a date using JavaScript. If you don’t want to change the original date object, create a copy and add weeks to the newly created copy. Thank you for reading.

Leave a Reply

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