Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add days to the now date in javascript?

var myDate = new Date();
var endtime= new Date(myDate.getDate()+1,23:59:59);
alert(endtime);

why there is no value of the endtime? if i want to add 1 day 10 hours 50 minute 30 second to the now time, how to wirte the endtime code? thank you

like image 649
250091017 Avatar asked Jul 05 '12 06:07

250091017


3 Answers

Try one of the two way will work for you...

function addDays(myDate,days) {
return new Date(myDate.getTime() + days*24*60*60*1000);
}

DEMO1

or

var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1); 

DEMO2

like image 131
Pranay Rana Avatar answered Oct 17 '22 15:10

Pranay Rana


try this

var date = new Date();
var numberToAdd = 1;
date.setDate(date.getDate() + numberToAdd); 
like image 6
Nikson Kanti Paul Avatar answered Oct 17 '22 13:10

Nikson Kanti Paul


You will need to add the days in milliseconds:

var tomorrow = new Date(Date.now() + 1 * 24*3600*1000);

Of course you can add various amounts of time, you just need to count it in milliseconds when using the Date constructor or set/getTime().

You can also set the different units one-by-one using their respective Date methods:

var sometime = new Date; // now
sometime.setDate(sometime.getDate() + numberOfDays); 
sometime.setHours(sometime.getHours() + numberOfHours); 
sometime.setMinutes(sometime.getMinutes() + numberOfMinutes);
...

You can't set the Date with a float value, it will be truncated when beeing converted to an Integer.

But the setter methods higher than milliseconds and higher than date have optional attributes, so that you can combine the setting:

var sometime = new Date; // now
sometime.setFullYear(
  sometime.getFullYear() + numberOfYears,
  sometime.getMonth() + numberOfMonths,
  sometime.getDate() + numberOfDays
); 
sometime.setHours(
  sometime.getHours() + numberOfHours,
  sometime.getMinutes() + numberOfMinutes,
  ...
);
like image 6
Bergi Avatar answered Oct 17 '22 14:10

Bergi