Convert Timestamp to Date in JavaScript

This tutorial will explain how we can convert the Unix timestamp to date in JavaScript. Unix timestamp is the time elapsed since the 1, Jan 1970 00:00:00 UTC, represented in seconds.

The JavaScript Date object contains the representation for the time elapsed since the 1, Jan 1970 00:00:00 UTC in milliseconds.

Convert Unix Timestamp to Date in JavaScript

When we create a new object from the Date() class using new Date(), it returns the time in milliseconds when it is created. If we need to get an object from the Date class at a specific point of time, we can pass the epoch timestamp to that class’s constructor.

var timestamp = 1607110465663
var date = new Date(timestamp);
console.log(date.getTime())
console.log(date)

Output:

1607110465663
2020-12-04T19:34:25.663Z

The Date class provides many methods to represent the Date in the preferred format like:

  1. getDate() returns the day of the calendar month 1 to 31 at that time.
  2. getMonth() returns the month number 0 to 11 at that time.
  3. getFullYear() returns the year in 4-digits format.
  4. getHours() returns the exact hour in 24-hour format for that time.
  5. getMinutes() returns the exact minutes 0 to 59 at that time.
  6. getSeconds() returns the exact seconds 0 to 59 at that time.
var timestamp = 1607110465663
var date = new Date(timestamp);

console.log("Date: "+date.getDate()+
          "/"+(date.getMonth()+1)+
          "/"+date.getFullYear()+
          " "+date.getHours()+
          ":"+date.getMinutes()+
          ":"+date.getSeconds());

Output:

Date: 4/12/2020 19:34:25

Since the JavaScript Date timestamp is in the unit of millisecond while the Unix timestamp is in the unit of second, we can multiply 1000 to convert the Unix timestamp to JavaScript timestamp. If the Unix timestamp is 1607110465, then the JavaScript timestamp is 1607110465000.

The following example demonstrates how we can convert the Unix timestamp to JavaScript Date timestamp.

var unixTimestamp = 62678980
var date = new Date(unixTimestamp*1000);
console.log("Unix Timestamp:",unixTimestamp)
console.log("Date Timestamp:",date.getTime())
console.log(date)
console.log("Date: "+date.getDate()+
          "/"+(date.getMonth()+1)+
          "/"+date.getFullYear()+
          " "+date.getHours()+
          ":"+date.getMinutes()+
          ":"+date.getSeconds());

Output:

Unix Timestamp: 62678980
Date Timestamp: 62678980000
Mon Dec 27 1971 12:49:40 GMT+0200 (Eastern European Standard Time)
Date: 27/12/1971 12:49:40
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Date

  • Add Days to Current Date in JavaScript