Skip to main content

How to Convert a Unix Timestamp to a Readable Time in JavaScript

A Unix timestamp represents a point in time as the number of seconds or milliseconds that have elapsed since the Unix Epoch (January 1, 1970). To display this to a user, you need to convert it into a human-readable format like 09:25 AM or "5 minutes ago."

This guide will teach you the modern, standard methods for formatting timestamps in JavaScript. You will learn how to use the powerful toLocaleTimeString() for localized output, how to build a custom time string manually, and how to create relative "time ago" strings.

The Core Step: Creating a Date Object from a Timestamp

Before you can format a timestamp, you must first convert it into a JavaScript Date object. This is the most critical step, and it has one common pitfall.

The Problem: The new Date() constructor expects a timestamp in milliseconds, but Unix timestamps are often provided in seconds.

The Solution: You must check your timestamp's unit. If it's in seconds, you need to multiply it by 1000 to convert it to milliseconds before passing it to the Date constructor.

const unixTimestampInSeconds = 1664000732;

// Multiply by 1000 to convert to milliseconds
const date = new Date(unixTimestampInSeconds * 1000);

console.log(date); // Output: Sat Sep 24 2022 09:25:32 GMT...

All subsequent formatting methods will be performed on this date object.

For displaying the time in a standard, user-friendly format, toLocaleTimeString() is the best practice. It automatically handles different locales (e.g., AM/PM vs. 24-hour clock) and provides great flexibility.

The Logic: the toLocaleTimeString() method takes two optional arguments: a locale string (like 'en-US' or 'en-GB') and an options object to control the output.

const date = new Date(1664000732 * 1000);

// Example 1: US-style time with AM/PM
const timeUS = date.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
});
console.log(timeUS); // Output: "09:25 AM"

// Example 2: British-style 24-hour time
const timeGB = date.toLocaleTimeString('en-GB', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
console.log(timeGB); // Output: "09:25:32"
note

This method is the professional standard for creating localized time strings.

Method 2: Manual Formatting for Custom Time Strings

If you need a specific, non-standard format (like HH-MM-SS), you can build the string manually using the Date object's methods.

The logic:

  1. Get the individual time components using getHours(), getMinutes(), and getSeconds().
  2. Pad each component with a leading zero if it's a single digit.
  3. Concatenate the components with your desired separators.

Solution:

function formatTime(date) {
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();

// Helper to add a leading zero
const padTo2Digits = (num) => num.toString().padStart(2, '0');

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

// Example Usage:
const date = new Date(1664000732 * 1000);
const customTime = formatTime(date);

console.log(customTime); // Output: "09:25:32"
note

This approach gives you complete control over the final output string.

Sometimes, you don't want a specific time but a relative format like "yesterday" or "5 days ago." The modern Intl.RelativeTimeFormat object is designed for this.

The logic:

  1. Calculate the difference between the timestamp and the current time.
  2. Convert this difference into the desired unit (e.g., days, hours).
  3. Use an Intl.RelativeTimeFormat object to format the difference into a localized string.

Solution:

function formatAsTimeAgo(timestamp) {
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
const oneDayInMs = 1000 * 60 * 60 * 24;

const daysDifference = Math.round(
(timestamp - new Date().getTime()) / oneDayInMs
);

return rtf.format(daysDifference, 'day');
}

// Example Usage:
const yesterdayTimestamp = new Date().setDate(new Date().getDate() - 1);

console.log(formatAsTimeAgo(new Date('2023-01-01').getTime())); // Output: "9 months ago"
console.log(formatAsTimeAgo(yesterdayTimestamp)); // Output: "yesterday"
  • numeric: 'auto': This option allows for friendly strings like "yesterday" instead of the more rigid "1 day ago."

Conclusion

Formatting a Unix timestamp in JavaScript is a simple process once you convert it to a Date object.

  • Remember to multiply your timestamp by 1000 if it's in seconds.
  • Use toLocaleTimeString() for standard, localized time formats. This is the recommended best practice.
  • Build the string manually with getHours() and other methods when you need a custom, non-standard format.
  • Use Intl.RelativeTimeFormat for modern, localized "time ago" strings.