Add days to date

OSCC · JavaScript, Date · Nov 28, 2020

Calculates the date of n days from the given date, returning its string representation.

  • Use the Date constructor to create a Date object from the first argument.
  • Use Date.prototype.getDate() and Date.prototype.setDate() to add n days to the given date.
  • Use Date.prototype.toISOString() to return a string in yyyy-mm-dd format.
const addDaysToDate = (date, n) => {
  const d = new Date(date);
  d.setDate(d.getDate() + n);
  return d.toISOString().split('T')[0];
};
addDaysToDate('2020-10-15', 10); // '2020-10-25'
addDaysToDate('2020-10-15', -10); // '2020-10-05'

Recommended snippets

  • Add minutes to date

    JavaScript, Date

    Calculates the date of n minutes from the given date, returning its string representation.

  • Add weekdays to date

    JavaScript, Date

    Calculates the date after adding the given number of business days.

  • Days ago

    JavaScript, Date

    Calculates the date of n days ago from today as a string representation.