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 unconditionally, but only when the difference to .endOf('day')
is not the whole hours I'd otherwise expect; and third, I want to round a moment.duration
, not a moment
.
Say I have a date/time stamp, "2017-02-17 21:00:00" and I want to find how many hours there are to the end of day. Mentally, if I think of 9 o'clock in the evening, I consider it 3 hours away from midnight, and that is the answer I'd want to obtain from momentjs. This is what I am doing (Javascript Web Console in Firefox):
var m1 = moment('2017-02-17 21:00:00');
<- undefined
var m2 = moment(m1).endOf('day');
<- undefined
m1
<- Object { _isAMomentObject: true, _i: "2017-02-17 21:00:00", _f: "YYYY-MM-DD HH:mm:ss", _isUTC: false, _pf: Object, _locale: Object, _a: Array[7], _d: Date 2017-02-17T20:00:00.000Z, _isValid: true, _z: null }
m2
<- Object { _isAMomentObject: true, _i: "2017-02-17 21:00:00", _f: "YYYY-MM-DD HH:mm:ss", _isUTC: false, _pf: Object, _locale: Object, _z: null, _a: Array[7], _d: Date 2017-02-17T22:59:59.999Z, _isValid: true }
var mdiff = moment(m2).diff(moment(m1))
<- undefined
mdiff
<- 10799999
var mddur = moment.duration(moment(m2).diff(moment(m1)))
<- undefined
mddur
<- Object { _isValid: true, _milliseconds: 10799999, _days: 0, _months: 0, _data: Object, _locale: Object }
So far, so good - now, to format the duration, I go as per Get the time difference between two datetimes (also duration formatting · Issue #1048 · moment/moment · GitHub); note that I want to use the same function I'd use to get correct durations larger than 24 hours to calculate this - even if this particular example has a duration shorter than 24h, so I use this:
Math.floor(mddur.asHours()) + moment.utc(mddur.asMilliseconds()).format(":mm:ss")
<- "2:59:59"
So, here I's want to obtain the answer "3:00:00" here, not "2:59:59" - though note, I'd still want "2:59:58" as is, and not rounded up.
I guess, if our duration in ms is 10799999, that is 10799999/1000=10799.999000 seconds, so if we have a duration that has millisecond remainder of 999 milliseconds, only then I would want a round up.
What would be the recommended way of achieving this with moment.js?
Ok, I ended up making a function that does what I want, here it is: