How to add N weeks to the current date in JavaScript

1 Answer

0 votes
/**
 * Adds a specified number of weeks to the current system date.
 * 
 * @param {number} weeks - The number of weeks to add (supports negative numbers to subtract).
 * @returns {Date} A new Date object representing the future date.
 */
function addWeeksToCurrentDate(weeks) {
    // 1. Create a new Date instance for the current time to avoid mutating global/external state
    const currentDate = new Date();
    
    // 2. Get the current day of the month and add the total days (1 week = 7 days)
    // setDate() automatically handles month/year rollovers and leap years.
    currentDate.setDate(currentDate.getDate() + weeks * 7);
    
    return currentDate;
}

// ==========================================
// Usage:
// ==========================================

const weeksToAdd = 4;
const futureDate = addWeeksToCurrentDate(weeksToAdd);

// Format the resulting date nicely as YYYY-MM-DD (ISO format)
const formattedDate = futureDate.toISOString().split('T')[0];

console.log(`Adding ${weeksToAdd} weeks gives: ${formattedDate}`);


/*
run:

Adding 4 weeks gives: 2026-12-05

*/

 



answered 1 day ago by avibootz
...