简体   繁体   中英

How to get the number of seconds between two dates in javascript?

Im trying to get the number of seconds between two dates in javascript.
Questions here and here suggest that a simple subtract operation should do the trick and other answers suggest that you use either the .getTime() or .valueOf() attributes.
But Despite all that when I subtract the two dates, Which are apart by 5 seconds I get the value 1551181475795 which is way too large to be correct.
Here is my code:

 var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf(); var dist = 347155200; // Update the count down every 1 second var x = setInterval(function() { // Get todays date and time var now = new Date("Mar 16, 2019 16:33:30"); // Find the distance between now and the count down date var distance = Math.abs(now - countDownDate / 1000); // Display the result in the element with id="demo" document.getElementById("demo").innerHTML = distance; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } }, 1000); 
 <p id='demo'> 

As you can see both times are only apart by 5 seconds but the value that separates them makes no sense.
Thanks in Advance!

It's a matter of operations order, you're dividing the countDownDate by 1000 before doing the subtraction (you're calculating now - countDownDate / 1000 however, you should calculate (now - countDownDate) / 1000 , subtraction first):

 var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf(); var dist = 347155200; // Update the count down every 1 second var x = setInterval(function() { // Get todays date and time var now = new Date("Mar 16, 2019 16:33:30"); // Find the distance between now and the count down date var distance = Math.abs((now - countDownDate) / 1000); // Display the result in the element with id="demo" document.getElementById("demo").innerHTML = distance; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } }, 1000); 
 <p id="demo"></p> 

As you had researched you can simply reduce the newer date from the older one which returns the milliseconds between the two dates.

Dividing that with 1000 gives you the seconds.

 let start = new Date("Mar 16, 2019 16:33:25") let end = new Date("Mar 16, 2019 16:33:30"); let secondsBetween = (end - start) / 1000; console.log("without value of:", secondsBetween, "seconds") start = new Date("Mar 16, 2019 16:33:25").valueOf() end = new Date("Mar 16, 2019 16:33:30").valueOf() secondsBetween = (end - start) / 1000; console.log("using value of:",(end - start) / 1000, "seconds") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM