How to Convert Unix Timestamp to Time in JavaScript

To convert Unix Timestamp to Time in JavaScript, you can “use the  toUTCString() method.”

Method 1: Using toUTCString()

In JavaScript, you can convert a Unix timestamp to a Date object and then format it as needed. A Unix timestamp is the number of seconds since January 1, 1970, 00:00:00 UTC.

However, the JavaScript Date object constructor expects milliseconds since January 1, 1970, 00:00:00 UTC. Therefore, when converting a Unix timestamp to a JavaScript Date object, you need to multiply the timestamp by 1000.

The toUTCString() method is used to represent the Date object as a string in the UTC format. 

Example

// Unix timestamp example 
// (this is the timestamp for 2023-08-26 00:00:00 UTC)
let unixTimestamp = 1680124800;

// Convert Unix timestamp to JavaScript Date object
let date = new Date(unixTimestamp * 1000);

// Format date to a human-readable string
// This will give you the date in UTC
let formattedDate = date.toUTCString();
console.log(formattedDate);

// This will give you the date in local timezone
let localFormattedDate = date.toLocaleString();
console.log(localFormattedDate);

Output

Unix Timestamp to Time in JavaScript

In this example:

  1. The date.toUTCString() gives you the date and time in UTC.
  2. The date.toLocaleString() gives you the date and time in the local timezone of the system where the code is running.

Method 2: Getting individual hours, minutes, and seconds

In JavaScript, timestamps are managed in milliseconds. To convert a UNIX timestamp, multiply it by 1000 to match JavaScript’s millisecond format.

Using the Date() function, we can then turn this value into a Date object.

To extract specific time details like hours, minutes, and seconds in JavaScript, you can use the getUTCHours(), getUTCMinutes(), and getUTCSeconds() methods.

For a neat display, numbers are transformed into strings and padded with zeros, if needed, using toString() and padStart(). These components are combined with colons to represent the complete time derived from the UNIX timestamp.

Example

function unixTimestampToTime(unixTimestamp) {
  // Convert Unix timestamp to JavaScript Date object
  let date = new Date(unixTimestamp * 1000);

  // Extract hours, minutes, and seconds from the Date object
  let hours = date.getUTCHours().toString().padStart(2, '0');
  let minutes = date.getUTCMinutes().toString().padStart(2, '0');
  let seconds = date.getUTCSeconds().toString().padStart(2, '0');

  // Format the extracted values
  let formattedTime = `${hours}:${minutes}:${seconds}`;

  return formattedTime;
}

// Example usage:
let unixTimestamp = 1680124800;

// This should print "00:00:00" for this example timestamp.
console.log(unixTimestampToTime(unixTimestamp));

Output

21:20:00

That’s it!

Related posts

JavaScript Timestamp to Date

JavaScript Date to Timestamp

JavaScript Date to String

JavaScript String to Date

JavaScript GMT to local time

Leave a Comment