Converting Timestamp to Date & Time in Javascript

javascript
Published on November 18, 2019

Use-Cases of this code snippet

  • Know how to convert unix timestamp to date & time formats (YYYY-MM-YY hh:mm:ss, MM/DD/YYYY, DD.MM.YYYY etc).
  • Know about Javascript's Date object and its methods.

A UNIX timestamp can be converted to the required date and time formats in Javascript using the Date() object and its methods.

Javascript

// unix timestamp
var ts = 1565605570;

// convert unix timestamp to milliseconds
var ts_ms = ts * 1000;

// initialize new Date object
var date_ob = new Date(ts_ms);

// year as 4 digits (YYYY)
var year = date_ob.getFullYear();

// month as 2 digits (MM)
var month = ("0" + (date_ob.getMonth() + 1)).slice(-2);

// date as 2 digits (DD)
var date = ("0" + date_ob.getDate()).slice(-2);

// hours as 2 digits (hh)
var hours = ("0" + date_ob.getHours()).slice(-2);

// minutes as 2 digits (mm)
var minutes = ("0" + date_ob.getMinutes()).slice(-2);

// seconds as 2 digits (ss)
var seconds = ("0" + date_ob.getSeconds()).slice(-2);

// date as YYYY-MM-DD format
console.log("Date as YYYY-MM-DD Format: " + year + "-" + month + "-" + date);

console.log("\r\n");

// date & time as YYYY-MM-DD hh:mm:ss format: 
console.log("Date as YYYY-MM-DD hh:mm:ss Format: " + year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds);

console.log("\r\n");

// time as hh:mm format: 
console.log("Time as hh:mm Format: " + hours + ":" + minutes);

Result :

Date as YYYY-MM-DD Format: 2019-8-12
Date as YYYY-MM-DD hh:mm:ss Format: 2019-8-12 15:56:10
Time as hh:mm Format: 15:56

Concepts & Methods Involved

  • Javascript's Date object accepts timestamp in milliseconds (not as seconds)
  • getFullYear() method returns the full 4 digit year for the provided timestamp.
  • getMonth() method returns the month for the provided timestamp (0-11). This needs to be incremented by 1 to get the actual calendar month.
  • getDate() method returns the date for the provided timestamp (1-31).
  • getHours() method returns the hour for the provided timestamp (0-23).
  • getMinutes() method returns the minutes for the provided timestamp (0-59).
  • getSeconds() method returns the seconds for the provided timestamp (0-59).
In this Tutorial