Table of Contents
Working with dates in JavaScript has historically been a challenge.
One of most commonly needed operations is how to add a number of days to a date to get a new date.
In this post, we'll look at the easiest way you can add a number of days to another date
Adding days to a date
Let's first start by creating a date object.
JAVASCRIPTconst date = new Date();
To increase the days on a Date, we can take advantage of the Date object's getDate()
and setDate()
methods.
More specifically, we can first get the original date's day, and then add the number of days we want to add to it.
Here's a long-form example of how we can add a number of days to a date:
JAVASCRIPTconst date = new Date();
const originalDay = date.getDate();
const daysToAdd = 5;
const newDay = originalDay + daysToAdd;
date.setDate(newDay);
We can turn this into a reusable function that we can call whenever we want to add any number of days to a date.
JAVASCRIPTconst addDays = (date, daysToAdd) => {
date.setDate(date.getDate() + daysToAdd);
};
const date = new Date();
addDays(date, 5);
Now you can easily add a week to a date by calling the function with addDays(date, 7)
, for example:
JAVASCRIPTconst date = new Date();
addDays(date, 7);
Conclusion
In this post, we created a function that lets us add any number of days to a date by modifying the date object.
We took advantage of the getDate()
and setDate()
to manipulate the original Date.
Hopefully, you've found this content useful and enjoyed reading it!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript