moment.js get current time in milliseconds?

前端 未结 7 1129
旧巷少年郎
旧巷少年郎 2021-02-01 11:54
var timeArr = moment().format(\'HH:mm:ss\').split(\':\');

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

This solution works,

相关标签:
7条回答
  • 2021-02-01 12:00

    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>

    0 讨论(0)
  • 2021-02-01 12:05
    var timeArr = moment().format('x');
    

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

    0 讨论(0)
  • 2021-02-01 12:12

    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 !

    0 讨论(0)
  • 2021-02-01 12:16

    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

    0 讨论(0)
  • 2021-02-01 12:16

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

    0 讨论(0)
  • 2021-02-01 12:18

    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()
    
    0 讨论(0)
提交回复
热议问题