Minutes since midnight in Momentjs

23,524

Solution 1

// Your moment
var mmt = moment();

// Your moment at midnight
var mmtMidnight = mmt.clone().startOf('day');

// Difference in minutes
var diffMinutes = mmt.diff(mmtMidnight, 'minutes');

By default, moment#diff will return number rounded down. If you want the floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned rounded number, not a rounded down number.

Consider this pseudocode because I haven't test to see if the difference takes into account DST.

Solution 2

This is what I have at the moment:

    if (!moment.isMoment(mmt)) {
        return 0;
    }
    var hh = mmt.get('hour');
    var mm = mmt.get('minute');
    return hh*60 + mm;

I am not sure if it takes into account various edge cases; comment if this is the case, or provide an alternate answer.

Share:
23,524
bguiz
Author by

bguiz

Writes Code.

Updated on June 21, 2020

Comments

  • bguiz
    bguiz almost 4 years

    In pure JS, this would be how.

    How can I find out the number of minutes since midnight for a given moment object (without extracting to Date)?

    • Must take into account DSTs
    • Minutes should be rounded
    • Must work with local time (not convert to UTC)