EN
JavaScript - convert unix timestamp to time
3
points
In this article, we would like to show you how to convert unix timestamp to HH:mm:ss
time in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const getTime = (timestamp) => {
const date = new Date(1000 * timestamp); // unix timestamp in seconds to milliseconds conversion
const time = date.toTimeString();
return time.substring(0, 8);
};
// Usage example:
const timestamp = 1630564245; // unix timestamp in seconds
console.log(getTime(timestamp)); // 08:30:45
Note:
In this example we multiply the timestamp by
1000
(to get milliseconds) and usetoTimeString()
to get the time string.
Alternative solution
In this example, we handle the string conversion in our own way.
Runnable example:
// ONLINE-RUNNER:browser;
const getString = (number) => number < 10 ? '0' + number : String(number);
// Converts unix timestamp in seconds to HH:mm:ss string.
//
const getTime = (timestamp) => {
const date = new Date(1000 * timestamp);
const hours = getString(date.getHours());
const minutes = getString(date.getMinutes());
const seconds = getString(date.getSeconds());
return `${hours}:${minutes}:${seconds}`;
};
// Usage example:
const timestamp = 1630564245; // unix timestamp in seconds
console.log(getTime(timestamp)); // 08:30:45