Convert milliseconds to hours and minutes using Mo

2020-02-09 06:08发布

问题:

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?

回答1:

I ended up doing this...

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


回答2:

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


回答3:

Using the moment-duration-format plugin:

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


回答4:

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

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


回答5:

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



回答6:

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



回答7:

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


回答8:

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



回答9:

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



回答10:

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