Reputation: 2072
I need to get the number of milliseconds of a certain day (even today), but need the result rounded down.
For example the number of milliseconds until this moment by using getTime()
method is 1432738826994
.
I would like to round this down to get the number of milliseconds until the beginning of the day, I need to get rid of all the minutes and hours. Is there a clean and simple way of achieving this?
Upvotes: 0
Views: 195
Reputation: 183
If you are happy with using an external library, the easiest way is with moment.js.
moment().startOf('day').valueOf();
Will give you the unix epoch value for the beginning of today's date.
If you want to use the Javascript built in date object, then you would either need to set the hours, minutes, seconds and milliseconds to 0:
var rightNow = new Date();
rightNow.setHours(0);
rightNow.setMinutes(0);
rightNow.setSeconds(0);
rightNow.setMilliseconds(0);
Or create a new object from just the year, month and day values:
var rightNow = new Date();
var earlierToday = new Date(rightNow.getFullYear(), rightNow.getMonth(), rightNow.getDate(), 0, 0, 0, 0);
Upvotes: 2
Reputation: 832
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var mi = d.getMilliseconds();
var fromStart = mi + (s * 1000) + (m * 60 * 1000) + (h * 60 * 60 * 1000);
var roundedDown = Date.now() - fromStart;
To print the start of the day use new Date(Date.now() - fromStart)
Upvotes: 2