Skip to content Skip to sidebar Skip to footer

Rounding Time Duration Of Difference To End Of Day To Whole Hours In Momentjs?

EDIT: This is not a duplicate of round up/ round down a momentjs moment to nearest minute - because first I don't want to round to nearest minute; second, I don't want to round unc

Solution 1:

Ok, I ended up making a function that does what I want, here it is:

function padDigits(number, digits) { // SO:10073699
  return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}

var durationToHoursStr = function(induration) {
  // copy the duration
  thisduration = moment.duration(induration);
  // to get seconds, we divide milliseconds with 1000;
  // check if the remainder of division of milliseconds with 1000 is 999:
  var remainder = thisduration.asMilliseconds() % 1000;
  //console.log("remainder", remainder);
  // only round up if the remainder is 999:
  if (remainder >= 999) {
    // in call moment.duration(Number), Number is interpreted as "length of time in milliseconds" (https://momentjs.com/docs/#/durations/)
    // so just add 1 ms, since anyways the previous remainder is 999, should be enough to flow over
    thisduration.add(moment.duration(1)); // should be in-place replacement - mutable
    //console.log("thisduration", thisduration);
  }
  return String(Math.floor(thisduration.asHours())) + ":" + padDigits(thisduration.minutes(), 2) + ":" + padDigits(thisduration.seconds(), 2);
};

var m1 = moment('2017-02-17 21:00:00');
var m2 = moment(m1).endOf('day');

// mdiff is int, total number of milliseconds, here 10799999
var mdiff = moment(m2).diff(moment(m1))

// mddur is moment.duration, also has the same amount of milliseconds, 
// mddur.asMilliseconds() = 10799999, mddur.asSeconds() = 10799.999, mddur.asHours() = 2.9999997222222223
var mddur = moment.duration(moment(m2).diff(moment(m1)));

var mddur_hoursString = durationToHoursStr(mddur);
console.log(mddur_hoursString); // prints "3:00:00"

var m3 = moment('2017-02-17 23:59:59');
var mddur3 = moment.duration(moment(m3).diff(moment(m1)));
var mddur3_hoursString = durationToHoursStr(mddur3);
console.log(mddur3_hoursString); // prints "2:59:59" - as it should, since we didn't really demand the difference to the end of day

Post a Comment for "Rounding Time Duration Of Difference To End Of Day To Whole Hours In Momentjs?"