How to convert a Unix timestamp to time in JavaScript ?

To convert a Unix timestamp (seconds since January 1, 1970) to a human-readable time in JavaScript, follow these steps:

1. Convert to Milliseconds

Unix timestamps are in seconds, but JavaScript’s Date uses milliseconds:

const unixTimestamp = 1622505600; // Example timestamp
const date = new Date(unixTimestamp * 1000); // Multiply by 1000

2. Extract Time Components

Use Date methods to get hours, minutes, and seconds.
Choose between local time or UTC:

Local Time (Browser’s Time Zone)

const hours = date.getHours();   // 0-23
const minutes = date.getMinutes(); // 0-59
const seconds = date.getSeconds(); // 0-59

UTC Time

const hours = date.getUTCHours();
const minutes = date.getUTCMinutes();
const seconds = date.getUTCSeconds();

3. Format with Leading Zeros

Ensure values like 9 become 09:

const pad = (num) => num.toString().padStart(2, '0');
const timeString = `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
// Example output: "08:05:09"

4. Complete Function

Combine everything into a reusable function:

function unixToTime(timestamp, useUTC = false) {
  const date = new Date(timestamp * 1000);
  const pad = (n) => n.toString().padStart(2, '0');

  const hours = useUTC ? date.getUTCHours() : date.getHours();
  const minutes = useUTC ? date.getUTCMinutes() : date.getMinutes();
  const seconds = useUTC ? date.getUTCSeconds() : date.getSeconds();

  return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
}

// Usage
console.log(unixToTime(1622505600)); // Local time (e.g., "00:00:00" UTC)
console.log(unixToTime(1622505600, true)); // UTC time ("00:00:00")

Alternative: Use toLocaleTimeString()

For locale-aware formatting (e.g., 12:00:00 AM):

const date = new Date(1622505600 * 1000);
const localTime = date.toLocaleTimeString('en-US');
// Example: "12:00:00 AM" (based on browser's locale)

Key Notes

  • Time Zones: Decide between local time (getHours()) or UTC (getUTCHours()).
  • Edge Cases: Handle invalid timestamps with checks (e.g., if (isNaN(date.getTime()))).
  • AM/PM Format: Use toLocaleTimeString() for 12-hour format:
  date.toLocaleTimeString('en-US', { hour12: true });
  // Example: "8:00:00 PM"

Example Outputs

Unix TimestampLocal Time (UTC+0)UTC Time
162250560000:00:0000:00:00
167890123412:34:5612:34:56

This method ensures accurate conversion and formatting for timestamps in vanilla JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *