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
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"
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
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);
Date object, development work will become more easy.