How do I get the current date or/and time in seconds using Javascript?
16 Answers
var seconds = new Date().getTime() / 1000;
....will give you the seconds since midnight, 1 Jan 1970
-
8@Nick - I think all examples are necessarily speculative and will sound contrived - but I'll take a shot :) Suppose you have data time stamped with unix time, and want to determine it's age. More though I think this is what is most likely meant by 'the current date/time in seconds'; just my gut feeling.– sje397Sep 30, 2010 at 12:10
-
5An application where I needed this was to work with a PHP back end as the time() function already returns this. It's also great for a time stamp as you can easily get the difference between time() being our current time and a time stamp from a previous time that had been stored in a database say when a user posted something. In the event you'd like to get a formatted time like 'October 22nd, 2015' you can craft your own function to return that from a timestamp as an argument or use one already here at Stack. Anyways, hope that gives you some insight as to when this would be useful. @NickCraver– uhfocuzOct 22, 2015 at 19:23
-
33It's worth noting that you want to wrap that in Math.floor(), else you get a decimal. Feb 12, 2016 at 18:43
-
18One way this would be useful would be calculating the time elapsed between two times.– ZacJun 12, 2016 at 20:22
-
4It would be useful in pretty much any elapsed time measurement with second-granularity that doesn't overflow. So like, in a lot of places.– shiggityDec 14, 2017 at 22:24
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.)
-
21This answer for milliseconds doesn't even answer the question that was asked. "How do I get the current date/time in seconds" Aug 17, 2020 at 21:53
-
6
-
4@magician11 -
Date.now() / 1000
also does not answer the question, because it gives values with partial fractions in milliseconds Sep 28, 2021 at 7:30 -
4
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:
- By default Javascript numbers are type 64 bit (double precision) floats, and bitwise operators implicitly convert that type into signed 32 bit integers. Arguably, the type should not be implicitly converted by the compiler, and instead the developer should make the conversion where needed.
- The signed 32 bit integer timestamp produced by the bitwise operator, causes the year 2038 problem as noted in the comments.
-
5
-
Note that flooring with the bitwise operator will result in the value being converted to a signed 32 bit integer. See Year 2038 problem.– RyanSep 21, 2021 at 17:29
-
@Ryan - thanks I've updated my answer to discourage the use of
| 0
Sep 22, 2021 at 22:07 -
-
1@AndreFigueiredo - Thank you for these examples. The solution I've provided was for the question "How do I get the current date/time in seconds in Javascript?", so your example in hours is not within context, but I do think your examples in seconds have some validity. In general, I still think
Math.round()
is best. But yes, I agree there are use cases where it's not best, andMath.floor()
andMath.ceil()
are more appropriate. I've updated my answer to note the same. Dec 9, 2021 at 3:47
Based on your comment, I think you're looking for something like this:
var timeout = new Date().getTime() + 15*60*1000; //add 15 minutes;
Then in your check, you're checking:
if(new Date().getTime() > timeout) {
alert("Session has expired");
}
To get the number of seconds from the Javascript epoch use:
date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;
// The Current Unix Timestamp
// 1443535752 seconds since Jan 01 1970. (UTC)
// Current time in seconds
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443535752
console.log(Math.floor(Date.now() / 1000)); // 1443535752
console.log(Math.floor(new Date().getTime() / 1000)); // 1443535752
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
jQuery
console.log(Math.floor($.now() / 1000)); // 1443535752
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
These JavaScript solutions give you the milliseconds or the seconds since the midnight, January 1st, 1970.
The IE 9+ solution(IE 8 or the older version doesn't support this.):
var timestampInMilliseconds = Date.now();
var timestampInSeconds = Date.now() / 1000; // A float value; not an integer.
timestampInSeconds = Math.floor(Date.now() / 1000); // Floor it to get the seconds.
timestampInSeconds = Date.now() / 1000 | 0; // Also you can do floor it like this.
timestampInSeconds = Math.round(Date.now() / 1000); // Round it to get the seconds.
To get more information about Date.now()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
The generic solution:
// ‘+’ operator makes the operand numeric.
// And ‘new’ operator can be used without the arguments ‘(……)’.
var timestampInMilliseconds = +new Date;
var timestampInSeconds = +new Date / 1000; // A float value; not an intger.
timestampInSeconds = Math.floor(+new Date / 1000); // Floor it to get the seconds.
timestampInSeconds = +new Date / 1000 | 0; // Also you can do floor it like this.
timestampInSeconds = Math.round(+new Date / 1000); // Round it to get the seconds.
Be careful to use, if you don't want something like this case.
if(1000000 < Math.round(1000000.2)) // false.
-
1
There is no need to initialize a variable to contain the Date object because Date.now()
is a static method which means that is accessible directly from an API object's constructor.
So you can just do this
const ms = Date.now()
const sec = Math.round(ms/1000)
document.write(`seconds: ${sec}`)
Something fun
Live update of seconds since January 1, 1970 00:00:00 UTC
const element = document.getElementById('root')
setInterval(() => {
let seconds = Math.round(Date.now()/1000)
element.innerHTML = seconds
},1000)
Seconds since January 1, 1970 00:00:00 UTC
<h1 id='root'></h1>
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.
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.
-
I do not know since when using language's side effects is a more elegant way. Mar 12, 2018 at 17:10
Better short cuts:
+new Date # Milliseconds since Linux epoch
+new Date / 1000 # Seconds since Linux epoch
Math.round(+new Date / 1000) #Seconds without decimals since Linux epoch
On some day in 2020, inside Chrome 80.0.3987.132, this gives 1584533105
~~(new Date()/1000) // 1584533105
Number.isInteger(~~(new Date()/1000)) // true
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. :)
if you simply need seconds in THREE JS, use one of the code bellow in function uses window.requestAnimationFrame()
let sec = parseInt(Date.now().toString()[10]); console.log(' counting Seconds => '+ sec );
or
let currentTime= Date.now();
let secAsString= time.toString()[10];
let sec = parseInt(t);
console.log('counting Seconds =>'+ sec );
-
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.– Community BotNov 5, 2021 at 3:59
A simple and quick way, without creating a date object and giving an integer as result (APIs accepting seconds will error if sending decimal)
var nowInSeconds = ~~(Date.now() / 1000);
console.log(nowInSeconds);