June 29, 2020
How to Get Milliseconds Between Two Dates in Javascript
In this tutorial, you will learn how to get milliseconds between two dates in javascript. Millisecond is one-thousandth of a second. Getting a difference in milliseconds between 2 dates is very easy to be achieved using the
Date
constructor in javascript. - We have selected 2 elements (
button
andh1
) using thedocument.querySelector()
method and stored them inbtn
andresult
variables. - Using the
Date
constructor, we created 2Date
objectsdate1
anddate2
of dates01/10/2020
and01/20/2020
respectively. - We have attached a
click
event listener to thebutton
element. Date
object hasgetTime()
method which returns the date in milliseconds. We are simply subtractingdate2
fromdate1
and displaying the result insideh1
element.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); let date1 = new Date('01/10/2020'); let date2 = new Date('01/20/2020'); btnGet.addEventListener('click', () => { result.innerText = date2.getTime() - date1.getTime(); });
In the following example, we have 2 hardcoded dates
01/10/2020
and01/20/2020
. We will use these dates with theDate
constructor to get theDate
object and display the difference on the screen in milliseconds. 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.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript