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, \
I ended up doing this...
var x = 433276000
var tempTime = moment.duration(x);
var y = tempTime.hours() + tempTime.minutes();
Using the moment-duration-format plugin:
moment.duration(ms).format("h:mm")
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).
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;
}
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
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.