Increment a date in javascript without using any libraries?

To increment a date in JavaScript without external libraries, use the setDate() method. This approach automatically handles month and year rollovers.

Using setDate() Method

The setDate() method accepts day values beyond the current month's range. JavaScript automatically adjusts the month and year when necessary.

let date = new Date('2024-01-31'); // January 31st
date.setDate(date.getDate() + 1);  // Add 1 day
console.log(date.toDateString());
Thu Feb 01 2024

Creating a Reusable Function

You can extend the Date prototype or create a standalone function to add days:

Date.prototype.addDays = function(days) {
    let d = new Date(this.valueOf());
    d.setDate(d.getDate() + days);
    return d;
}

let today = new Date('2024-12-31');
let tomorrow = today.addDays(1);

console.log('Today:', today.toDateString());
console.log('Tomorrow:', tomorrow.toDateString());
Today: Tue Dec 31 2024
Tomorrow: Wed Jan 01 2025

Standalone Function Approach

function addDays(date, days) {
    let result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
}

let startDate = new Date('2024-02-28');
let newDate = addDays(startDate, 2);

console.log('Start:', startDate.toDateString());
console.log('After 2 days:', newDate.toDateString());
Start: Wed Feb 28 2024
After 2 days: Fri Mar 01 2024

Adding Different Time Units

let date = new Date('2024-06-15');

// Add 7 days
let nextWeek = new Date(date);
nextWeek.setDate(date.getDate() + 7);

// Add 1 month
let nextMonth = new Date(date);
nextMonth.setMonth(date.getMonth() + 1);

// Add 1 year
let nextYear = new Date(date);
nextYear.setFullYear(date.getFullYear() + 1);

console.log('Original:', date.toDateString());
console.log('Next week:', nextWeek.toDateString());
console.log('Next month:', nextMonth.toDateString());
console.log('Next year:', nextYear.toDateString());
Original: Sat Jun 15 2024
Next week: Sat Jun 22 2024
Next month: Mon Jul 15 2024
Next year: Sun Jun 15 2025

Conclusion

Use setDate() with getDate() + days to increment dates reliably. JavaScript automatically handles month and year boundaries, making this the simplest approach for date manipulation without libraries.

Updated on: 2026-03-15T23:18:59+05:30

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements