user3214545
user3214545

Reputation: 2213

Convert milliseconds to hours and minutes using Momentjs

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?

Upvotes: 51

Views: 115262

Answers (12)

Bennyb123
Bennyb123

Reputation: 33

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

Upvotes: 0

Anthony M.
Anthony M.

Reputation: 146

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.

Upvotes: 2

srbcheema1
srbcheema1

Reputation: 618

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".

Upvotes: 1

Batman
Batman

Reputation: 91

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

Upvotes: -3

brickgale
brickgale

Reputation: 61

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

Upvotes: 2

Scott Puleo
Scott Puleo

Reputation: 3684

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;
}

Upvotes: 2

strictlyk3v
strictlyk3v

Reputation: 572

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

var milliseconds = 1000;
moment.utc(milliseconds).format('HH:mm');

Upvotes: 34

dmmd
dmmd

Reputation: 3009

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

Upvotes: 10

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241959

Using the moment-duration-format plugin:

moment.duration(ms).format("h:mm")

Upvotes: 21

user3214545
user3214545

Reputation: 2213

I ended up doing this...

var x = 433276000
var tempTime = moment.duration(x);
var y = tempTime.hours() + tempTime.minutes();

Upvotes: 72

closure
closure

Reputation: 7452

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

Upvotes: 33

djechlin
djechlin

Reputation: 60848

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

Upvotes: 2

Related Questions