Given a unix timestamp such as 1424321864000 (Thu Feb 19 2015 04:57:44 GMT+0000) I would like to convert this to 1424318400000 (Thu Feb 19 2015 04:00:00 GMT+0000).
In other words I want to keep the timestamp exactly as is just remove the minutes, seconds, milliseconds from it. Whatever timestamp is input would return the same timestamp for exactly that day/time 'on its hour'.
There are two ways I can think of doing this. A library such as Luxon can handle this in a fairly straight-forward method:
const topOfHour = DateTime.fromMillis(initialTimestamp).startOf('hour');
There's also a matching endOf
function if you need that.
The pure-javascript method works too but is a little messy:
const initialDate = new Date(initialTimestamp);
const zeroMilliseconds = new Date(initialDate.setMilliseconds(0));
const zeroSeconds = new Date(zeroMilliseconds.setSeconds(0));
const startOfHour = new Date(zeroSeconds.setMinutes(0));
I want to acknowledge user756659's comment with some slightly more verbose code that I missed when checking documentation.
const initialDate = new Date(initialTimestamp);
const startOfHour = new Date(initialDate.setMinutes(0, 0, 0))
It could be pared down to a one-liner, but I'm keeping it verbose here for readability.