[javascript] moment.js get current time in milliseconds?

var timeArr = moment().format('HH:mm:ss').split(':');

var timeInMilliseconds = (timeArr[0] * 3600000) + (timeArr[1] * 60000);

This solution works, test it, but I'd rather just use the moment api instead of using my own code.

This code returns TODAYS time in milliseconds. I need it to call another function in milliseconds...Can not use the epoch. Need today's time formated in milliseconds. 9:00am = 3.24e+7 milliseconds 9:00pm = 6.84e+7 milliseconds.

This question is related to javascript momentjs

The answer is


You can just get the individual time components and calculate the total. You seem to be expecting Moment to already have this feature neatly packaged up for you, but it doesn't. I doubt it's something that people have a need for very often.

Example:

_x000D_
_x000D_
var m = moment();_x000D_
_x000D_
var ms = m.milliseconds() + 1000 * (m.seconds() + 60 * (m.minutes() + 60 * m.hours()));_x000D_
_x000D_
console.log(ms);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_


You could subtract the current time stamp from 12 AM of the same day.

Using current timestamp:

moment().valueOf() - moment().startOf('day').valueOf()

Using arbitrary day:

moment(someDate).valueOf() - moment(someDate).startOf('day').valueOf()

From the docs: http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

So use either of these:


moment(...).valueOf()

to parse a preexisting date and convert the representation to a unix timestamp


moment().valueOf()

for the current unix timestamp


var timeArr = moment().format('x');

returns the Unix Millisecond Timestamp as per the format() documentation.


Since this thread is the first one from Google I found, one accurate and lazy way I found is :

const momentObject = moment().toObject();
// date doesn't exist with duration, but day does so use it instead
//   -1 because moment start from date 1, but a duration start from 0
const durationCompatibleObject = { ... momentObject, day: momentObject.date - 1 };
delete durationCompatibleObject.date;

const yourDuration = moment.duration(durationCompatibleObject);
// yourDuration.asMilliseconds()

now just add some prototypes (such as toDuration()) / .asMilliseconds() into moment and you can easily switch to milliseconds() or whatever !


To get the current time's milliseconds, use http://momentjs.com/docs/#/get-set/millisecond/

var timeInMilliseconds = moment().milliseconds();

See this link http://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/

valueOf() is the function you're looking for.

Editing my answer (OP wants milliseconds of today, not since epoch)

You want the milliseconds() function OR you could go the route of moment().valueOf()