moment.js get current time in milliseconds?

纵然是瞬间 提交于 2019-12-04 08:46:41

问题


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.


回答1:


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




回答2:


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()




回答3:


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

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




回答4:


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()



回答5:


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:

var m = moment();

var ms = m.milliseconds() + 1000 * (m.seconds() + 60 * (m.minutes() + 60 * m.hours()));

console.log(ms);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>



回答6:


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 !




回答7:


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

var timeInMilliseconds = moment().milliseconds();


来源:https://stackoverflow.com/questions/39980722/moment-js-get-current-time-in-milliseconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!