0
0
JavascriptHow-ToBeginner · 3 min read

How to Add Days to Date in JavaScript Easily

To add days to a date in JavaScript, create a Date object and use setDate() with the current day plus the number of days to add. This updates the date correctly, even across months and years.
📐

Syntax

Use the Date object's setDate() method to add days. The syntax is:

  • date.setDate(date.getDate() + daysToAdd)

Here, date is your Date object, and daysToAdd is the number of days you want to add.

javascript
date.setDate(date.getDate() + daysToAdd);
💻

Example

This example shows how to add 5 days to the current date and print the new date.

javascript
const date = new Date();
console.log('Original date:', date.toDateString());

const daysToAdd = 5;
date.setDate(date.getDate() + daysToAdd);
console.log('New date:', date.toDateString());
Output
Original date: Sat Jun 15 2024 New date: Thu Jun 20 2024
⚠️

Common Pitfalls

One common mistake is trying to add days by manipulating the timestamp directly without using setDate(). Also, forgetting that setDate() automatically adjusts the month and year if the day goes beyond the current month.

Wrong approach example:

javascript
// Wrong: Adding days by adding milliseconds manually (can cause errors if daylight saving changes occur)
const date = new Date();
const daysToAdd = 5;
const wrongNewDate = new Date(date.getTime() + daysToAdd * 24 * 60 * 60 * 1000);
console.log('Wrong new date:', wrongNewDate.toDateString());

// Right: Using setDate()
date.setDate(date.getDate() + daysToAdd);
console.log('Correct new date:', date.toDateString());
Output
Wrong new date: Thu Jun 20 2024 Correct new date: Thu Jun 20 2024
📊

Quick Reference

MethodDescription
getDate()Returns the day of the month (1-31)
setDate(day)Sets the day of the month, adjusts month/year if needed
getTime()Returns timestamp in milliseconds
toDateString()Returns a readable date string

Key Takeaways

Use date.setDate(date.getDate() + days) to add days safely.
setDate() automatically handles month and year changes.
Avoid adding days by manipulating timestamps directly to prevent errors.
Use toDateString() to display dates in a readable format.