1

How can i add 5 days to the current date, and then convert it to a string representing the local date and time?

const newDate = new Date();

const test = newDate.setDate(newDate.getDate() + 5).toLocaleString();

Just returns the number of milliseconds.. (same if i use toString().

Gambit2007
  • 3,260
  • 13
  • 46
  • 86
  • Does this answer your question? [Add days to JavaScript Date](https://stackoverflow.com/questions/563406/add-days-to-javascript-date) – maraaaaaaaa Jan 17 '22 at 16:54

3 Answers3

2

The easiest way is by using a date library like Moment.js or date-fns. I gave an example below using date-fns and addDays

const newDate = new Date();
const fiveDaysLater = addDays(newDate, 5);
Nathan Wiles
  • 841
  • 10
  • 30
  • That's exactly what i'm trying to avoid.. (using a library) – Gambit2007 Jan 17 '22 at 16:53
  • I vote for this as I cannot find a way to add days with pure JS especially for scenario when the current date is the last day of the month. The moment JS solution is the only way it increments the month along with day if current date is last day of the month – Carlos Jaime C. De Leon Jul 31 '23 at 03:50
2

Without using any libraries, Vanilla JS solution:

const now = new Date()
const inFiveDays = new Date(new Date(now).setDate(now.getDate() + 5))
console.log('now', now.toLocaleString())
console.log('inFiveDays', inFiveDays.toLocaleString())

This even works when your date overflows the current month.

gru
  • 2,319
  • 6
  • 24
  • 39
0

Just use new Date() in front of it.

const newDate = new Date();
const add  =5
const test = newDate.setDate(newDate.getDate() + add)
console.log(new Date(test).toLocaleString());
James
  • 2,732
  • 2
  • 5
  • 28