Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert minutes to hours using moment.js

Can anyone tell me how to convert minutes to hours using moment.js and display in hh:mm A format.

For example, If minutes is 480 it should display output as 08:00 AM. If minutes is 1080 it should display output as 06:00 PM

like image 388
user1268130 Avatar asked Mar 16 '16 12:03

user1268130


2 Answers

Assuming that you always want to add minutes from midnight, the easiest thing to do is:

moment.utc().startOf('day').add(480, 'minutes').format('hh:mm A')

The use of UTC avoids issues with daylight saving time transitions that would cause the time to vary based on the day in question.

If you actually want the number of minutes after midnight on a given day, including the DST transitions take out the utc and just use:

moment().startOf('day').add(480, 'minutes').format('hh:mm A')

Note that the accepted answer has potential issues with DST transitions. For instance if you are in a part of the United States that observes DST:

moment('2016-03-13').hours(2).minutes(30).format('hh:mm A')
"03:30 AM"

The result is not as expected, and will vary between going back and hour or going forward an hour depending on the browser.

Edit: Original answer has been updated to fix bug. As an additional comment, I would be extremely leery of any code that attempts to map a number of minutes to civil time. The bottom line is that 480 minutes into the day is not always 8:00 AM. Consider this in the context of your problem. DST bugs are likely right now.

like image 163
Maggie Pint Avatar answered Sep 22 '22 09:09

Maggie Pint


You can just do the basic arithmetic like so:

function getTimeFromMins(mins) {
    // do not include the first validation check if you want, for example,
    // getTimeFromMins(1530) to equal getTimeFromMins(90) (i.e. mins rollover)
    if (mins >= 24 * 60 || mins < 0) {
        throw new RangeError("Valid input should be greater than or equal to 0 and less than 1440.");
    }
    var h = mins / 60 | 0,
        m = mins % 60 | 0;
    return moment.utc().hours(h).minutes(m).format("hh:mm A");
}


getTimeFromMins(480); // returns "08:00 AM"
getTimeFromMins(520); // returns "08:40 AM"
getTimeFromMins(1080); // returns "06:00 PM"
like image 42
user162097 Avatar answered Sep 23 '22 09:09

user162097