1

I am trying to add 5 days to today's date using JavaScript. I am also trying to add this function into a button so that the result comes in an alert box when I click it, not as soon as I open the page.

I am new to JavaScript and trying very hard to learn.

Any help? Thanks!

user2262982
  • 41
  • 1
  • 3
  • 4

5 Answers5

9

Declare a Date variable (it will be set to current date/time):

var dt = new Date();

Add 5 days:

dt.setDate(dt.getDate() + 5);

Put all the above in your click handler function. Something like:

document.getElementById('dateBtn').onclick = function () {
   var dt = new Date();
   dt.setDate(dt.getDate() + 5);
   alert(dt);
};

FIDDLE EXAMPLE

Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
  • How do we incorporate edge cases? Like adding 5 days to Aug 30 should be September 5 if adding 6 days? – AutoMate Jul 15 '20 at 18:57
  • @Gauzdx I am not sure I understood your question, JavaScript Date engine should take care of days in months, gap years and all this kind of stuff. Is there some specific code you are testing that gives you unexpected results? – Artyom Neustroev Aug 11 '20 at 12:01
4
var date = new Date();          // Get current Date

date.setDate(date.getDate()+5); // add 5 days to the current date

For more information see Date.

Zeta
  • 103,620
  • 13
  • 194
  • 236
1

Might be overkill but moment.js could be useful to you.

Bryce
  • 106
  • 6
1

create a Date instance five days:

var fiveDaysLater = new Date( AnyYourDate.getTime() );
fiveDaysLater.setDate(fiveDaysLater.getDate() + 5);
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
1

JavaScript stores dates and times in milliseconds. So, add 5 days worth:

var fiveDaysLater = new Date(0,0,0,0,0,0,Date.now() + 5 * 24 * 60 * 60 * 1000);

Date.now() returns a value in milliseconds. The date constructor (new Date) then makes a new Date object (hence the keyword new) using this value, plus the five days of milliseconds, and initializes the variable fiveDaysLater.

HardScale
  • 971
  • 1
  • 7
  • 18