Table of Contents
In this post, we will see how to convert Convert epoch time to Date Javascript.
There are multiple ways to do it. Let’s go through them.
Using Date’s setUTCSeconds()
To convert epoch time to Date in Javascript:
- Create
Date
object by passing 0 in its constructor. When you pass 0 to Date’s constructor, it will set date to epoch. - Pass utc seconds to
setUTCSeconds()
method onDate
object
1 2 3 4 5 6 |
var utcSeconds = 1639876543; var d = new Date(0 d.setUTCSeconds(utcSeconds); console.log(d); |
Output:
1 2 3 |
2021-12-19T01:15:43.000Z |
We created new Date object and called setUTCSeconds()
method on date object.
Using Date’s constructor()
To convert epoch time to Date in Javascript:
- Multiply epoch seconds by 1000.
- Pass it to Date’s constructor.
1 2 3 4 5 |
var utcSeconds = 1639876543; var d = new Date(utcSeconds*1000); // The 0 there is the key, which sets the date to the epoch console.log(d); |
Output:
1 2 3 |
2021-12-19T01:15:43.000Z |
We multiplied epoch time with 1000 to convert it to milliseconds and passed it to Date
‘s constructor.
Convert epoch to yyyy-mm-dd in Javascript
In case, you need to convert epoch time to date format yyyy-mm-dd, you can use following code:
1 2 3 4 5 6 |
var utcSeconds = 1639876543; var date = new Date(utcSeconds*1000); var resultFormat = date.toISOString().split('T')[0] console.log(resultFormat); |
Output:
1 2 3 |
2021-12-19 |
The part before T
is in required format YYYY-MM-DD
, so we get split and get first part of ISO String.
That’s all about how to convert epoch time to Date in Javascript.