Languages
[Edit]
EN

JavaScript - convert unix timestamp to time

0 points
Created by:
Aston-Freeman
397

In this article, we would like to show you how to convert unix timestamp to Date 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();
  const parts = time.split(' ');
  return parts[0];
};

// 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 convertion on our own, so we can get the time string in any format.

Runnable example:

// ONLINE-RUNNER:browser;

const getTime = (timestamp) => {
    const date = new Date(1000 * timestamp); // unix timestamp in seconds to milliseconds conversion
    const data = [date.getHours(), date.getMinutes(), date.getSeconds()];
    for (i = 0; i < data.length; i++) {
        if (data[i] < 10) {
          	data[i] = '0' + data[i];
        }
    }
    return `${data[0]}:${data[1]}:${data[2]}`;
};

// Usage example:
let timestamp = 1630564245;       // unix timestamp in seconds
console.log(getTime(timestamp));  // 08:30:45

Output:

08:30:45
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