178

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?

chandan
  • 2,400
  • 2
  • 18
  • 23

4 Answers4

327

To find the Unix Timestamp in seconds:

moment().unix()

The documentation is your friend. :)

abagshaw
  • 6,162
  • 4
  • 38
  • 76
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
155

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 deprecated, and alternatives like Luxon or date-fns are suggested. See: https://momentjs.com/docs/#/-project-status

S. C.
  • 110
  • 1
  • 13
mix3d
  • 4,122
  • 2
  • 25
  • 47
26

for UNIX time-stamp in milliseconds

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

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

django
  • 2,809
  • 5
  • 47
  • 80
23

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
kumar chandraketu
  • 2,232
  • 2
  • 20
  • 25