Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Set a new Date to tomorrow 8am

I want to make a Javascript date object eg. var now = new Date().getTime() that is set for "tomorrow at 8am", how would I accomplish that?

like image 898
Barry Michael Doyle Avatar asked Mar 22 '16 15:03

Barry Michael Doyle


2 Answers

You could do the following:

var now  = new Date();
now.setDate(now.getDate() + 1)
now.setHours(8);
now.setMinutes(0);
now.setMilliseconds(0);

also check this

You could also: var now = Date("2016-03-23T8:00:00");

And var now = new Date(2016,03,23,8,0,0,0 );

like image 171
Rana Avatar answered Oct 11 '22 11:10

Rana


If you have a lot of date arithmetics, I can only strongly recommend the use of moment.js.

Using this library, your code would be as short as moment().add(1, 'days').hours(8).startOf('hour').

moment.js works with 'moment' objects that wrap over JS dates to provide additional methods. The moment() invocation returns a moment of the current datetime, thus being the moment.js equivalent to new Date().
From there we can use the moment.js methods, as add(quantity, unit) that adds a duration to the previous date. All these manipulation methods return a modified moment, which mean we can chain them.
The hours() methods is both a getter and a setter depending on its arguments ; here we provide it with a number, which mean we set the moment's hour part to 8. A call to .hours() would have instead returned the current hour part.
startOf(unit) returns a moment at the start of the unit, meaning it will set all lesser units to 0 : moment().startOf('day') would return today's 00:00 am.

like image 26
Aaron Avatar answered Oct 11 '22 09:10

Aaron