2
7

Convert Epoch to Date Time in JavaScript

Reading Time: < 1 minute

We may need to convert Epoch Epoch to Date Time in JavaScript since JavaScript is using the concept of Epoch in its Date object. Here, we will explore the methods to perform these conversion.

To understand more about Epoch, we have an article with more description here.

Methods to Convert Epoch to Date Time

  • Initialise Epoch to Date
  • Use setUTCSeconds method

Initialise Epoch to Date

Here, we will first define the number of seconds and convert it to milliseconds. Subsequently, we will pass it into new Date() object. This will initialise Epoch to Date immediately.

const unixSeconds = 1650248817;
const unixMilliSeconds = unixSeconds * 1000;
const myDate = new Date(unixMilliSeconds);

console.log(myDate.toLocaleString());     // "18/04/2022, 10:26:57"
console.log(myDate.toLocaleTimeString()); // "10:26:57"

Use setUTCSeconds method

First, we will create a date object and assign 0 to create the Date object with 1st January 1790. Then we pass Epoch time in seconds to setUTCSeconds method. We can use this method is we do not know the time during initialisation and need it during processing runtime.

const unixSeconds = 1650248817;
const myDate = new Date(0);
myDate.setUTCSeconds(unixSeconds);

console.log(myDate.toLocaleString());     // "18/04/2022, 10:26:57"
console.log(myDate.toLocaleTimeString()); // "10:26:57"

Convert to number of days

Since we know that JavaScript Date() starts from Epoch Time by default, we can also easily retrieve the number of days since Epoch for any date.

const myDate = new Date(1650248817 * 1000);
let fullDaysSinceEpoch = Math.floor( myDate / 8.64e7);  
console.log(fullDaysSinceEpoch); // 19100

const now = Date.now();
fullDaysSinceEpoch = Math.floor( now / 8.64e7);
console.log(fullDaysSinceEpoch);

Conclusion

We have seen 2 methods to convert Epoch to JavaScript either through initialise phase or within processing runtime. With the full understanding of Epoch and JavaScript Date object, development work will become more easy.

Show Comments

No Responses Yet

Leave a Reply