How to extract time from Unix timestamp using JavaScript?

Hey everyone! I’m working on a project where I’ve got Unix timestamps stored in my MySQL database. These timestamps are then sent to my JavaScript code. I’m trying to figure out how to display just the time part from these timestamps.

Here’s what I’m aiming for:

const unixTimestamp = 1625097600; // Example timestamp
const formattedTime = formatUnixTime(unixTimestamp);
console.log(formattedTime); // Should output something like '14:30:00'

I’m looking for a way to create this formatUnixTime function that takes a Unix timestamp and returns the time in ‘HH:MM:SS’ format. Any ideas on how to approach this? I’ve tried a few things but can’t seem to get it right. Thanks in advance for your help!

hey, try this:

function formatUnixTime(ts) {
return new Date(ts * 1000).toTimeString().slice(0,8);
}

works fine for me, maybe adjust for timezone nuances. cheers!

Here’s a straightforward approach that should work for your needs:

function formatUnixTime(timestamp) {
const date = new Date(timestamp * 1000);
return date.toISOString().substr(11, 8);
}

This method converts the Unix timestamp to milliseconds, creates a Date object, then uses toISOString() to get a standardized string representation. We then extract just the time portion using substr().

One benefit of this approach is that it always returns UTC time, which can be useful for consistency across different timezones. If you need local time instead, you could modify it to use toLocaleTimeString() with appropriate options.

Remember to handle potential errors, especially if your timestamps might be invalid.

I’ve dealt with Unix timestamps a lot in my projects, and here’s a reliable approach I’ve found:

function formatUnixTime(timestamp) {
  const date = new Date(timestamp * 1000);
  return date.toLocaleTimeString('en-US', { hour12: false });
}

This function converts the Unix timestamp to milliseconds (hence the * 1000), creates a Date object, and then uses toLocaleTimeString() to format it. The ‘en-US’ locale and hour12: false option ensure you get a 24-hour format.

One advantage of this method is it automatically handles timezone conversions based on the user’s system settings. If you need a specific timezone, you can add that as an option too. Hope this helps!