Explain Codes LogoExplain Codes Logo

How to convert unix timestamp to calendar date moment.js

javascript
momentjs
timestamp-conversion
date-formatting
Alex KataevbyAlex Kataev·Jan 4, 2025
TLDR

To convert a Unix timestamp into a date with moment.js, use this quick command:

var date = moment.unix(UNIX_TIMESTAMP).format("YYYY-MM-DD HH:mm");

In which, UNIX_TIMESTAMP should be replaced with your specific numeric timestamp to yield a formatted date string.

If you wish to opt for localized formatting, try out this snippet:

var localDate = moment.unix(UNIX_TIMESTAMP).format('L');

Take note, moment.js expects Unix timestamps to be in seconds. Always validate your timestamp for seamless conversions.

The Not-So-Obvious: Timestamp Nuances and Time Zones

Seconds Matter

Unix timestamps tick in terms of seconds since January 1, 1970, UTC. JavaScript Date objects, on the other hand, use milliseconds. This distinction is crucial when working with moment.unix():

// I got 99 problems, but milliseconds ain't one! var jsDate = new Date(UNIX_TIMESTAMP * 1000);

Dancing with Time Zones

Translating dates between time zones is akin to a complex choreography. Good news is, moment.js can gracefully execute this dance with the tz() function:

// Let's "timezone" our way outta here! var zonedDate = moment.unix(UNIX_TIMESTAMP).tz('America/New_York').format("YYYY-MM-DD HH:mm");

Pro-tip: Always verify the validity of the timestamp before conversion to avoid any "Invalid date" dramas.

Conversion Essentials: Input Processing and Validation

Checking the Inputs

Before diving into conversions, take a moment (pun intended!) to validate your timestamp. Simple checks can save major headaches:

  • Is it a number, not a string?
  • Does it represent seconds since the epoch (not milliseconds or something else)?
  • Is it within the realm of reasonability?

Special Cases & Oh-No Moments

"Hope for the best, prepare for the worst"—this principle also applies well to handling edge cases in timestamp conversions as well as for undefined or null inputs. Ensure your elbow-grease code can handle all these without breaking a sweat.

// Schrödinger's cat: caught between a valid and invalid timestamp var date = moment.unix(UNIX_TIMESTAMP); if (date.isValid()) { console.log(date.format("YYYY-MM-DD HH:mm")); } else { console.log("Invalid timestamp"); }

Always confirm the accuracy of the conversion by checking the output against the expected outcome. That's your quality assurance!

Tips & Tricks for Practical Applications

Transitions to JS Date

Need a JavaScript Date object? Moment.js has got you covered with the toDate() method:

// Your moment of becoming a Date... object! var jsDateObject = moment.unix(UNIX_TIMESTAMP).toDate();

Testing Your Mettle

Be proactive and verify edge cases such as leap years, the epoch time, and weirdly formatted dates. Your code's resilience is worth the effort!

Time Zone Prowess

Coupling moment.tz() effortlessly with format allows you to handle regional settings as easily as sipping your coffee.

// Handling timezones, easier than handling my cat! var zonedDate = moment.unix(UNIX_TIMESTAMP).tz('America/New_York').format("YYYY-MM-DD HH:mm");