Files
30-seconds-of-code/snippets/addDaysToDate.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

727 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
addDaysToDate date,intermediate 2020-10-12T03:03:18+03:00 2020-11-28T19:18:29+02:00

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

  • Use new Date() 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'