DEV Community

LuisPa
LuisPa

Posted on

3 2

Adding days to a date using Vanilla JS

This is a short post about how we can manage a common situation with our propper implementation.

Despite the JavaScript Date warts, it’s straightforward to add days to a date in JavaScript.

Today we have a ton of libraries and external modules to work with dates. It's overwhelming!

While it would be very easy to reach for moment.js or another date manipulation library (date-fns, luxon, dayjs) to do something as simple as adding days to a Date in JavaScript, writing a short helper function might just be easier.

A utility function that creates a Date copy

function addDays(date, days) {
  const copy = new Date(Number(date))
  copy.setDate(date.getDate() + days)
  return copy
}

const date = new Date();
const newDate = addDays(date, 10);
Enter fullscreen mode Exit fullscreen mode

Mutating the Date directly

const date = new Date();
date.setDate(date.getDate() + 10);
Enter fullscreen mode Exit fullscreen mode

Gotchas and examples

This actually works as expected, eg. the month rolls over.

const d = new Date('2019-04-14');

const monthRollsOver = addDays(myDate, 31);
console.log(monthsRollOver)
// 2019-05-15
Enter fullscreen mode Exit fullscreen mode

Of course, if you’re already using a data manipulation library elsewhere in your code, you should leverage that since you’re already paying the download/parse cost.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Good for mentioning rollover, otherwise I would live in fear, not using .getDate() (Well, I can totally rely on .getTime() or +Date.)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more