July 1, 2020
How to Get Seconds Between Two Dates in Javascript
- We have selected
button
andh1
elements using thedocument.querySelector()
method and stored them inbtnGet
andresult
variables respectively. - We got instances of both dates using the
Date
constructor and stored them indate1
anddate2
variables. - We have attached the
click
event listener to thebutton
element. - Each
Date
instance has thegetTime()
method which returns the number of milliseconds. - Inside the
click
event handler function, we are using this method with both instances of date and subtracting the number of milliseconds returned bydate1
from the number of milliseconds returned bydate2
and storing the result in thems
variable. - We need the number of seconds, so we are simply dividing milliseconds by 1000 and displaying the result in the
h1
element.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); let date1 = new Date('01/01/2020'); let date2 = new Date('01/03/2020'); btnGet.addEventListener('click', () => { let ms = date2.getTime() - date1.getTime(); let second = 1000; result.innerText = ms/second; });
In the following example, we have 2 dates
01/01/2020
and01/03/2020
. We will simply grab the difference in the number of seconds between these 2 dates using theDate
constructor and display the result on the screen. Please have a look over the code example and steps given below.HTML & CSS
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements.“Get”
and for the h1 element is“Result”
.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript