How can I get seconds since epoch in Javascript?
JavascriptDatetimeJavascript Problem Overview
On Unix, I can run date '+%s'
to get the amount of seconds since epoch. But I need to query that in a browser front-end, not back-end.
Is there a way to find out seconds since Epoch in JavaScript?
Javascript Solutions
Solution 1 - Javascript
var seconds = new Date() / 1000;
Or, for a less hacky version:
var d = new Date();
var seconds = d.getTime() / 1000;
Don't forget to Math.floor()
or Math.round()
to round to nearest whole number or you might get a very odd decimal that you don't want:
var d = new Date();
var seconds = Math.round(d.getTime() / 1000);
Solution 2 - Javascript
Try this:
new Date().getTime() / 1000
You might want to use Math.floor()
or Math.round()
to cut milliseconds fraction.
Solution 3 - Javascript
You wanted seconds since epoch
function seconds_since_epoch(){ return Math.floor( Date.now() / 1000 ) }
example use
foo = seconds_since_epoch();
Solution 4 - Javascript
The above solutions use instance properties. Another way is to use the class property Date.now
:
var time_in_millis = Date.now();
var time_in_seconds = time_in_millis / 1000;
If you want time_in_seconds to be an integer you have 2 options:
a. If you want to be consistent with C style truncation:
time_in_seconds_int = time_in_seconds >= 0 ?
Math.floor(time_in_seconds) : Math.ceil(time_in_seconds);
b. If you want to just have the mathematical definition of integer division to hold, just take the floor. (Python's integer division does this).
time_in_seconds_int = Math.floor(time_in_seconds);
Solution 5 - Javascript
If you want only seconds as a whole number without the decimals representing milliseconds still attached, use this:
var seconds = Math.floor(new Date() / 1000);
Solution 6 - Javascript
You can create a Date object (which will have the current time in it) and then call getTime()
to get the ms since epoch.
var ms = new Date().getTime();
If you want seconds, then divide it by 1000:
var sec = new Date().getTime() / 1000;
Solution 7 - Javascript
My preferred way:
var msEpoch = (+new Date());
var sEpoch = (+new Date()) / 1000;
For more information on the +
jump down the rabbit hole.
Solution 8 - Javascript
The most simple version:
Math.floor(Date.now() / 1000)
Solution 9 - Javascript
EPOCH means time from 01 January 1970
var date = new Date();
Following line will return the number of milliseconds from 01 Jaunary 1970
var ms = date.getTime();
Following line will convert milliseconds to seconds
var seconds = Math.floor(ms/1000);
console.log("Seconds since epoch =",seconds);
Solution 10 - Javascript
In chrome you can open the console with F12 and test the following code:
var date = new Date().getTime()
console.debug('date: ' + date);
if (Date.now() < date)
console.debug('ko');
else
console.debug('ok');