DEV Community

Ephraim Chukwu
Ephraim Chukwu

Posted on

How to Convert Epoch Timestamp to Date Using JavaScript

Being a relatively new language that ushered in the use of time in seconds, Solidity provides a global feature called block.timestamp. In this short piece, I explain how you can convert epoch timestamp emitted from your backend solidity contracts into appropriate date that includes day, month, year and time.

The Unix Epoch dates back to 1st of January, 1970. This aided computer system globally in tracking time in relation to dated information. It has been widely adopted in many computer languages, dynamic applications and sophisticated ecosystem.

Due to the bignumberish state of the time generated, questions around how this will be used, especially for frontend web3 developers, lure many into a state of brainstorming.

Here is the simple solution:

function getDate(x) {
   const myDate = new Date(x * 1000);
   return myDate;
}
Enter fullscreen mode Exit fullscreen mode

The x passed into the above function is the epoch timestamp that comes in this form:

1601528702

It is multiplied by 1000 so as to convert it from milliseconds to seconds.

The return value from the code snippet above gives us a range of choice to make. This returns a full text string generated from your browser's time zone. We can thereafter convert these beads of texts to a locale string, to string, or if we are interested in the time zone representation, using the in-built JavaScript attributes.

For better clarification, the following are possible manipulation.

 myDate.toLocaleString(); // '3/24/2022, 2:06:03 AM'
 myDate.toGMTString(); // 'Thu, 24 Mar 2022 01:06:03 GMT'
 myDate.toJSON(); // '2022-03-24T01:06:03.440Z'
 myDate.toDaateString(); // 'Thu Mar 24 2022'
Enter fullscreen mode Exit fullscreen mode

You can do well to check out other inherent methods that JavaScript provides aside from the ones above.

Apart from block.timestamp that requires the expertise of developers to manipulate from the knowledge of clients and users of our decentralized application, there are other features such as the conversion of wei to ether, block.number, msg.data etc.

I hope this helps. Keep enjoying your codes.

Top comments (0)