48

I am new to Momentjs. I am trying to use it to convert milliseconds to hours and minutes. Below, x is milliseconds

x = 433276000
var y = moment.duration(x, 'milliseconds').asHours;

Can anyone help?

user3214545
  • 2,103
  • 3
  • 20
  • 26

12 Answers12

72

I ended up doing this...

var x = 433276000
var tempTime = moment.duration(x);
var y = tempTime.hours() + tempTime.minutes();
user3214545
  • 2,103
  • 3
  • 20
  • 26
33

Try this:

var x = 433276000
var d = moment.duration(x, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
console.log("hours:" + hours + " mins:" + mins);
closure
  • 7,412
  • 1
  • 23
  • 23
33

You can create a Moment.js date from milliseconds using moment.utc().

var milliseconds = 1000;
moment.utc(milliseconds).format('HH:mm');
strictlyk3v
  • 562
  • 5
  • 7
21

Using the moment-duration-format plugin:

moment.duration(ms).format("h:mm")
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
10

There is an easier way to achieve what you want.

This

moment('2000-01-01 00:00:00').add(moment.duration(1000)).format('HH:mm:ss');

Will output this

00:00:01

Not the fanciest, I know, but it is 100% pure moment js.

edit: Doesn't work for periods longer than 24h

dmmd
  • 2,938
  • 4
  • 33
  • 41
2

This seems unsupported per this SO. Following this github issue, there's a moment-to-countdown plugin that you may be able to use.

But it seems you may want Countdown.js for this in the first place.

countdown(0, 433276000, countdown.HOURS | countdown.MINUTES).toString();

Note this does not take into account leap seconds, or leap anything for that matter, as it fixes to the Unix epoch (so it's not a pure time interval).

Community
  • 1
  • 1
djechlin
  • 59,258
  • 35
  • 162
  • 290
2

There really is no need to use Moment for this operation.

It can be written in a single line:

var hours = Math.round((450616708 / 1000 / 60 / 60) * 100) / 100;

or as function:

function millisecondsToHours(ms){
  return Math.round((ms / 1000 / 60 / 60) * 100) / 100;
}
Scott Puleo
  • 3,684
  • 24
  • 23
2

In Moment.js duration you can just use Math.trunc for hours if you are expecting it to be over 24hrs. hh:mm:ss format.

var seconds = moment.duration(value).seconds();
var minutes = moment.duration(value).minutes();
var hours = Math.trunc(moment.duration(value).asHours());

see it here: https://codepen.io/brickgale/pen/mWqKJv?editors=1011

brickgale
  • 61
  • 3
2

Here is a function that formats it for you into a string.

function ms_to_str(val) {

    let tempTime = moment.duration(val),
        timeObj = {
            years: tempTime.years(),
            months: tempTime.months(),
            days: tempTime.days(),
            hrs: tempTime.hours(),
            mins: tempTime.minutes(),
            secs: tempTime.seconds(),
            ms: tempTime.milliseconds()
        },

        timeArr = [];

    for (let k in timeObj) {
        if (Number(timeObj[k]) > 0) {
            timeArr.push(`${timeObj[k]} ${k}`)
        }
    }

    return timeArr.join(', ');
}

Then simply call ms_to_str(2443253) which returns 40 mins, 43 secs, 253 ms.

If you do not need to show milliseconds, simply comment off the ms: tempTime.milliseconds().toString().padStart(3, '0') line.

Anthony M.
  • 98
  • 5
1

Momentjs itself doesn't support duration, in order to do so, we need a plugin moment-duration-format

To use this plugin follow these steps (for React-js)

import moment from 'moment';
import momentDurationFormatSetup from "moment-duration-format";

var time = moment.duration(value,unit).format('hh:mm:ss',{trim:false})

Note: I have used {trim: false} as extra parameter so that it doesn't trim out extra 0's in the beginning. You can omit it if you want "11:30" instead of "00:11:30".

srbcheema1
  • 544
  • 4
  • 16
0
function durationAsString(ms, maxPrecission = 3) {
    const duration = moment.duration(ms)

    const items = []
    items.push({ timeUnit: 'd', value: Math.floor(duration.asDays()) })
    items.push({ timeUnit: 'h', value: duration.hours() })
    items.push({ timeUnit: 'm', value: duration.minutes() })
    items.push({ timeUnit: 's', value: duration.seconds() })

    const formattedItems = items.reduce((accumulator, { value, timeUnit }) => {
        if (accumulator.length >= maxPrecission || (accumulator.length === 0 && value === 0)) {
            return accumulator
        }

        accumulator.push(`${value}${timeUnit}`)
        return accumulator
    }, [])

    return formattedItems.length !== 0 ? formattedItems.join(' ') : '-'
}

Lets you set max-precision and will not show insignificant values. Examples:

durationAsString(0) will return -

durationAsString(10000) will return 10s

durationAsString(100000) will return 1m 40s

durationAsString(10000000) will return 2h 46m 40s

durationAsString(100000000) will return 1d 3h 46m

durationAsString(100000000, 4) will return 1d 3h 46m 40s

Bennyb123
  • 33
  • 6
-3

moment('2000-01-01 00:00:00').millisecond(XXXXXX).format("HH:mm:ss")

Batman
  • 91
  • 1
  • 6