Reputation: 10608
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?
Upvotes: 10
Views: 15572
Reputation: 24802
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.
Upvotes: 8