Reputation: 514
I'm trying to get the epoch time from exactly 1 hour ago, rounded to the highest minute. E.g: 19:17:01 should become 19:18:00 & 19:17:59 should become 19:18:00 etc.
I already know how to convert Date (Minus 1 hour) to Epoch:
var dat = new Date();
dat.setHours( dat.getHours() - 1 );
var epochstart = Date.parse(dat)
console.log(epochstart) //Returns e.g. 19:17:01 in epoch (Milliseconds) time
This works and everything but how would I round the date to the minute UP?
And, if possible, I want to convert the milliseconds to seconds (I can just remove the last 3 chars)
Upvotes: 1
Views: 2172
Reputation: 147483
One approach is to round the time value up to the nearest full minute, which will also zero the seconds and milliseconds at the same time:
/* Set date to next full minute or current time
* if at exctly 0 minutes and 0 milliseconds
* @param {Date} date - start date
* @returns {Date} new Date set to next full minute
*/
function getNextFullMinute(date) {
return new Date(date - (date % 6e4) + 6e4);
}
// Format options
let dateOpts = {
hour: 'numeric',
minute:'2-digit',
hour12: false
};
// Get a Date set to the start of the next minute
let date = getNextFullMinute(new Date());
console.log(`The next full minute is at ${date.toLocaleString(void 0, dateOpts)}.`);
Upvotes: 0
Reputation: 1507
The way you managed to change the hour, similarly, you can change the minutes and seconds. Based on your ask, below is a possible solution:
let dat = new Date();
dat.setHours(dat.getHours() - 1);
if (dat.getSeconds() > 0) {
dat.setMinutes(dat.getMinutes() + 1);
dat.setSeconds(0);
}
const epochstart = Date.parse(dat);
console.log(dat.toString());
console.log(epochstart);
As for converting milliseconds to seconds, divide epochstart
by 1000.
Upvotes: 2