Explain Codes LogoExplain Codes Logo

Convert a Unix timestamp to time in JavaScript

javascript
unix-timestamp
time-formatting
date-object
Nikita BarsukovbyNikita Barsukov·Aug 10, 2024
TLDR

Quickly convert a Unix timestamp to a JavaScript Date object with new Date(timestamp * 1000). For a human-friendly presentation, use the toLocaleString() method:

const unixTimestamp = 1609459200; // New Year's Eve excitement const date = new Date(unixTimestamp * 1000); // Bang! Capsule landing console.log(date.toLocaleString()); // '1/1/2021, 12:00:00 AM' if you're GMT lucky

For time content only, utilize toLocaleTimeString():

console.log(date.toLocaleTimeString('en-US')); // Your carriage awaits at '12:00:00 AM'

Deep dive to the rabbit hole

On the fly time extraction

After popping a Date object from a Unix timestamp capsule, extract the specific time points:

let hours = date.getHours(); // Find out the hour let minutes = date.getMinutes().toString().padStart(2, '0'); // Don't forget the minutes! let seconds = date.getSeconds().toString().padStart(2, '0'); // ...and the seconds too let time = `${hours}:${minutes}:${seconds}`; // Stitch together to get the 'HH:MM:SS' fairytale

Make it feel like home

The toLocaleTimeString() method conveniently handles locale-specific time formatting:

console.log(date.toLocaleTimeString()); // Time wearing cultural attire

And for more customized locales and options, use your creative powers on Intl.DateTimeFormat:

let formatter = new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); console.log(formatter.format(date)); // Custom masquerade in time ball

The timezone-neutral meeting point

To obtain a timezone-neutral time string, utilize toISOString:

console.log(date.toISOString().slice(11, 19)); // Rounds off to 'HH:MM:SS' from ISO string

Traps and trolls in the coding forest

  • Be mindful that your Unix timestamp is a seconds-ticked bomb, not a milliseconds one.
  • Beware of time zones leaping out when displaying times.
  • Use the cover of .toLocaleTimeString() over .toString() for better readability.
  • Lay the bricks of polyfill for a safe bridge to legacy browser land.

Pro wizard tips and tricks

Handy-dandy time formatting tool

Create yourself a reusable magic wand function for shining on Unix timestamps:

function formatUnixTimestamp(unixTimestamp, format = 'en-US') { const date = new Date(unixTimestamp * 1000); // Cast your time spell here return date.toLocaleTimeString(format); // Voila! Your time beast is tamed! } console.log(formatUnixTimestamp(1609459200)); // Wave your magic wand!

Ward off the evil spirits

One evil spell is incorrect formatting; make sure you're not ensnared by HH/MM/SS when it's really HH:MM:SS. And remember to multiply the Unix timestamp by 1000—it's ravenous for milliseconds!

Battle-proofing your code

Combat test your magic wand function:

console.log(formatUnixTimestamp(0)); // Time travel to the dawn of Unix time. Pack your Unix epoch survival kit!

By entering the field with ready-to-use weapons, you prepare for a successful assault in the real coding world battles.

In the end

As Merlin said: "The most powerful magic requires the most tenacity and practice." Give my answer a wand wave! Enjoy your time-travel adventures! 🧙‍♀️🗝🕰