How do I get the current date or/and time in seconds using Javascript?
To get the current date and time in seconds: Copied! const date = new Date(); const dateTimeInSeconds = Math. floor(date. getTime() / 1000); // 👇️ 164328461 console.
Use the time. time() function to get the current time in seconds since the epoch as a floating-point number. This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00. It returns the current time in seconds.
Use the getTime() method to get a UTC timestamp, e.g. new Date(). getTime() . The method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Calling the method from any time zone returns the same UTC timestamp.
var seconds = new Date().getTime() / 1000;
....will give you the seconds since midnight, 1 Jan 1970
Reference
Date.now()
gives milliseconds since epoch. No need to use new
.
Check out the reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
(Not supported in IE8.)
Using new Date().getTime() / 1000
is an incomplete solution for obtaining the seconds, because it produces timestamps with floating-point units.
new Date() / 1000; // 1405792936.933
// Technically, .933 would be in milliseconds
Instead use:
Math.round(Date.now() / 1000); // 1405792937
// Or
Math.floor(Date.now() / 1000); // 1405792936
// Or
Math.ceil(Date.now() / 1000); // 1405792937
// Note: In general, I recommend `Math.round()`,
// but there are use cases where
// `Math.floor()` and `Math.ceil()`
// might be better suited.
Also, values without floats are safer for conditional statements, because the granularity you obtain with floats may cause unwanted results. For example:
if (1405792936.993 < 1405792937) // true
Warning: Bitwise operators can cause issues when used to manipulate timestamps. For example, (new Date() / 1000) | 0
can also be used to "floor" the value into seconds, however that code causes the following issues:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With