Javascript show milliseconds as days:hours:mins without seconds
Something like this?
function dhm(t){
var cd = 24 * 60 * 60 * 1000,
ch = 60 * 60 * 1000,
d = Math.floor(t / cd),
h = Math.floor( (t - d * cd) / ch),
m = Math.round( (t - d * cd - h * ch) / 60000),
pad = function(n){ return n < 10 ? '0' + n : n; };
if( m === 60 ){
h++;
m = 0;
}
if( h === 24 ){
d++;
h = 0;
}
return [d, pad(h), pad(m)].join(':');
}
console.log( dhm( 3 * 24 * 60 * 60 * 1000 ) );
Dont know why but the others didn't worked for me so here is mine
function dhm (ms) {
const days = Math.floor(ms / (24*60*60*1000));
const daysms = ms % (24*60*60*1000);
const hours = Math.floor(daysms / (60*60*1000));
const hoursms = ms % (60*60*1000);
const minutes = Math.floor(hoursms / (60*1000));
const minutesms = ms % (60*1000);
const sec = Math.floor(minutesms / 1000);
return days + ":" + hours + ":" + minutes + ":" + sec;
}
Sounds like a job for Moment.js.
var diff = new moment.duration(ms);
diff.asDays(); // # of days in the duration
diff.asHours(); // # of hours in the duration
diff.asMinutes(); // # of minutes in the duration
There are a ton of other ways to format durations in MomentJS. The docs are very comprehensive.
Here you go:
http://jsfiddle.net/uNnfH/1
Or if you don't want to play with a running example, then:
window.minutesPerDay = 60 * 24;
function pad(number) {
var result = "" + number;
if (result.length < 2) {
result = "0" + result;
}
return result;
}
function millisToDaysHoursMinutes(millis) {
var seconds = millis / 1000;
var totalMinutes = seconds / 60;
var days = totalMinutes / minutesPerDay;
totalMinutes -= minutesPerDay * days;
var hours = totalMinutes / 60;
totalMinutes -= hours * 60;
return days + "." + pad(hours) + "." + pad(totalMinutes);
}