DEV Community

Hugo Di Francesco
Hugo Di Francesco

Posted on • Originally published at codewithhugo.com on

5 3

Add days to a Date in vanilla JavaScript

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

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);

Mutating the Date directly

const date = new Date();
date.setDate(date.getDate() + 10);

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

Find the live examples at: observablehq.com/@hugodf/add-days-to-a-javascript-date

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

unsplash-logo
Wim van 't Einde

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (3)

Collapse
 
saigkill profile image
Sascha Manns

Hi Hugo. Thanks for sharing this stuff. I'm everytime interested to see Vanilla stuff.

Collapse
 
hugo__df profile image
Hugo Di Francesco

Glad to hear that, I run a JS best-practices etc newsletter at buttondown.email/hugo

Collapse
 
saigkill profile image
Sascha Manns

Subscribed :-)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs