How to convert a Unix timestamp to time in JavaScript?

To convert a Unix timestamp to time in JavaScript, you need to multiply the timestamp by 1000 (since Unix timestamps are in seconds, but JavaScript Date expects milliseconds) and then use Date methods to extract time components.

What is a Unix Timestamp?

A Unix timestamp represents the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC. JavaScript's Date constructor expects milliseconds, so we multiply by 1000.

Example

<html>
  <head>
    <title>JavaScript Dates</title>
  </head>
  <body>
    <script>
      var unix_time = 1514791901;
      var date = new Date(unix_time * 1000);

      // get hours
      var hrs = date.getHours();

      // get minutes
      var min = "0" + date.getMinutes();

      // get seconds
      var sec = "0" + date.getSeconds();

      document.write("Time- " + hrs + ":" + min.substr(-2) + ":" + sec.substr(-2));
    </script>
  </body>
</html>

Output

Time- 13:01:41

Alternative Approach Using Modern JavaScript

const unix_time = 1514791901;
const date = new Date(unix_time * 1000);

// Format time using toLocaleTimeString()
const timeString = date.toLocaleTimeString();
console.log("Time:", timeString);

// Manual formatting with padStart()
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');

console.log(`Time- ${hours}:${minutes}:${seconds}`);
Time: 1:01:41 PM
Time- 13:01:41

Key Points

  • Multiply Unix timestamp by 1000 to convert seconds to milliseconds
  • Use substr(-2) or padStart(2, '0') to ensure two-digit formatting
  • toLocaleTimeString() provides locale-specific time formatting
  • Manual formatting gives you full control over the output format

Conclusion

Converting Unix timestamps to time requires multiplying by 1000 and using Date methods. Modern JavaScript offers cleaner formatting options with padStart() and toLocaleTimeString().

Updated on: 2026-03-15T23:18:59+05:30

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements