/ #javascript #date 

Add days to a Date in vanilla JavaScript

Despite the JavaScript Date warts, it’s straightforward to add day(s) 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.

Table of Contents

Add days to a new instance of JavaScript Date

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

Update a JavaScript Date with added days

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

Add a day to a JavaScript Date

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

Add a week to a JavaScript Date

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

Gotchas and examples: months in JavaScript dates roll over

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

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

const monthRollsOver = addDays(myDate, 31);
// 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-logoWim van 't Einde


Hugo Di Francesco

Co-author of "Professional JavaScript" with Packt. He runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon and Elsevier.

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.