Languages
[Edit]
EN

JavaScript - convert unix timestamp to time

3 points
Created by:
Aston-Freeman
787

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 use toTimeString() 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

 

Alternative titles

  1. JavaScript - convert unix seconds time to time
  2. JavaScript - convert unix seconds time to HH:mm:ss time
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - convert unix timestamp to time

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join