How do I get the current date/time in seconds in Javascript?
You can met another way to get time in seconds/milliseconds since 1 Jan 1970:
var milliseconds = +new Date;
var seconds = milliseconds / 1000;
But be careful with such approach, cause it might be tricky to read and understand it.
To get today's total seconds of the day:
getTodaysTotalSeconds(){
let date = new Date();
return +(date.getHours() * 60 * 60) + (date.getMinutes() * 60) + date.getSeconds();
}
I have add +
in return which return in int
. This may help to other developers. :)
Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000
This should give you the milliseconds from the beginning of the day.
(Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000)/1000
This should give you seconds.
(Date.now()-(Date.now()/1000/60/60/24|0)*24*60*60*1000)/1000
Same as previous except uses a bitwise operator to floor the amount of days.
I use this:
Math.round(Date.now() / 1000)
No need for new object creation (see doc Date.now())
var seconds = new Date().getTime() / 1000;
....will give you the seconds since midnight, 1 Jan 1970
Reference
To get the number of seconds from the Javascript epoch use:
date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;