How to add N weeks to the current date in TypeScript

1 Answer

0 votes
/**
 * Adds a specified number of weeks to the current system date.
 * 
 * @param weeks - The number of weeks to add (supports negative numbers to subtract).
 * @returns A new Date object representing the future date.
 */
function addWeeksToCurrentDate(weeks: number): Date {
    // 1. Create a new Date instance for the current time to ensure purity and avoid side effects
    const currentDate: Date = new Date();
    
    // 2. Calculate total days (1 week = 7 days) and add them via setDate()
    // setDate() automatically handles month/year rollovers, end-of-month bounds, and leap years.
    currentDate.setDate(currentDate.getDate() + weeks * 7);
    
    return currentDate;
}

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

const weeksToAdd: number = 4;
const futureDate: Date = addWeeksToCurrentDate(weeksToAdd);

// Format the resulting date nicely as YYYY-MM-DD (ISO format)
const formattedDate: string = 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
...