Explain Codes LogoExplain Codes Logo

How to return the current timestamp with Moment.js?

javascript
moment-js
timestamp
date-object
Nikita BarsukovbyNikita Barsukov·Feb 20, 2025
TLDR

To get the current Unix timestamp with Moment.js, call moment().unix(). This returns the number of seconds since the Unix Epoch (January 1, 1970).

const unixTimestamp = moment().unix(); // Now you're a time traveler!

Need the timestamp in milliseconds? Use the valueOf method often utilized for JavaScript Date operations:

const millisecondTimestamp = moment().valueOf(); // Because every millisecond counts!

Both methods provide a no-nonsense way to handle timestamps.

Handling precision

If you're into precision and need your timestamps right down to the milliseconds, Moment.js is here for you:

const preciseTimestamp = moment().valueOf(); // Like splitting hairs but with time

Or just be cool and use the shorthand:

const shorthandTimestamp = +moment(); // Isn't shorthand grand?

Remember, valueOf or shorthand is your friend when playing with JavaScript's Date object or APIs expecting millisecond timestamps.

For the human eyes

To make people (and not machines) understand your timestamp, format it:

const formatted = moment().format("YYYY-MM-DD HH:mm:ss"); // Makes more sense now, doesn't it?

With an arsenal of formatting options, Moment.js helps you mold your timestamp into the human-readable form your project demands, such as HH:mm for hours and minutes.

Complying with standards: ISO and RFC

The ISO 8601 and the RFC 3339 are not just any formats. They are your timestamp's passport in the digital realm:

const isoString = moment().toISOString(); // The international language of time

Remember, standards are key when pouring timestamps into different systems and across borders.

Time comparison: A moment's game

Need to figure if two moments in time are identical? There's an isSame method for that:

const startTime = moment(); const endTime = moment(); const sameTime = startTime.isSame(endTime); // Are we twinning?

Comparisons are your go-to solvers for logic checks, validations, and time-driven events.

Deeper dive: Complexities and nuances

There are nuances and complexities in time handling that could make you feel like Alice in Wonderland. Time zones, leap seconds, and the differences between ISO 8601 and RFC 3339 are some of these. Consult Moment.js' documentation to make sense of it all.