June 29, 2020
How to Convert Timestamp to Date Format in Javascript
- We have selected 2 elements (
button
andh1
) using thedocument.querySelector()
method and stored them inbtn
andresult
variables. - We have created a global variable
timestamp
and assigned1578162600000
as a value. - We have added a
click
event listener to thebutton
element. - We are passing the
timestamp
variable to theDate
constructor which returns aDate
object. - We are getting
month
,year
, anddate
by callinggetMonth()
,getFullYear()
, andgetDate()
methods respectively ofDate
object.getMonth()
method returns an integer between 0 and 11, where January is 0, February is 1, and so on. That’s why we are adding 1 to a month to get the correct digit for the month. - We are simply creating a template string with
month
,year
, anddate
variables and displaying it insideh1
element.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); //1/5/2020 let timestamp = 1578162600000; btnGet.addEventListener('click', () => { let dateObj = new Date(timestamp); let month = dateObj.getMonth() + 1; let year = dateObj.getFullYear(); let date = dateObj.getDate(); result.innerText = `${month}/${date}/${year}`; });
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