Getting current unixtimestamp using Moment.js

Unix TimestampMomentjs

Unix Timestamp Problem Overview


I want to get the Unix TimeStamp using Moment.js. I can find many functions which convert timestamp to date in moment.js. I know that I can easily get the unix timestamp by using the following JavaScript function: Math.floor(new Date().getTime()/1000).

But I want to use Moment.js to get the same result. Is there any direct function in moment.js to get the current timestamp?

Unix Timestamp Solutions


Solution 1 - Unix Timestamp

To find the Unix Timestamp in seconds:

moment().unix()

The documentation is your friend. :)

Solution 2 - Unix Timestamp

For anyone who finds this page looking for unix timestamp w/ milliseconds, the documentation says

moment().valueOf()

or

+moment();

you can also get it through moment().format('x') (or .format('X') [capital X] for unix seconds with decimal milliseconds), but that will give you a string. Which moment.js won't actually parse back afterwards, unless you convert/cast it back to a number first.

NOTE: This answer continues to get +1s, which is nice, but Moment has been depreciated, and alternatives like Luxon or date-fns are suggested. See: https://momentjs.com/docs/#/-project-status

Solution 3 - Unix Timestamp

for UNIX time-stamp in milliseconds

moment().format('x') // lowerCase x

for UNIX time-stamp in seconds moment().format('X') // capital X

Solution 4 - Unix Timestamp

Try any of these

valof = moment().valueOf();            // xxxxxxxxxxxxx
getTime = moment().toDate().getTime(); // xxxxxxxxxxxxx
unixTime =  moment().unix();           // xxxxxxxxxx
formatTimex =  moment().format('x');   // xxxxxxxxxx
unixFormatX = moment().format('X');    // xxxxxxxxxx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchandanView Question on Stackoverflow
Solution 1 - Unix TimestampMatt Johnson-PintView Answer on Stackoverflow
Solution 2 - Unix Timestampmix3dView Answer on Stackoverflow
Solution 3 - Unix TimestampdjangoView Answer on Stackoverflow
Solution 4 - Unix Timestampkumar chandraketuView Answer on Stackoverflow