When calling duration(param)
, the parameter must be one of the values described in the docs: https://momentjs.com/docs/#/durations/creating/
ex: if you call it like moment.duration(100)
, this creates a duration of 100 milliseconds. A duration represents a span of elapsed time, or an "amount of time".
If you pass a date object to it (moment.duration(d)
), this doesn't make sense. You're trying to create a duration (a span of elapsed time) from a date value. And that's a misunderstanding of 2 concepts:
- a date/time represents a specific point in the calendar
- a duration represents a span of elapsed time, and it's not attached to any specific point in the calendar
You can do things like:
- calculate the difference between 2 dates: the result is a duration (between today 10 AM and tomorrow 2 PM, the difference - the duration is 28 hours - not considering DST effects: https://www.timeanddate.com/time/dst/transition.html)
- add/subtract a duration to a date: today 8 AM, plus a duration of 2 hours, equals today 10 AM
But creating a duration from a date, without having another date as reference, doesn't make sense. In this specific case, moment just decided to return a duration with the value equals to zero: print the value of moment.duration(d)
, you'll see P0T
- that's the ISO 8601 representation of a zero-duration: https://en.wikipedia.org/wiki/ISO_8601#Durations
Then you call .asMilliseconds()
, that returns the total amount of milliseconds that the duration represents. In this case, it's returning zero.
Then you call moment.utc()
passing the result above as parameter. In other words, you're doing the same as moment.utc(0)
. When you pass a number to utc()
, it interprets this number as "the number of milliseconds since Unix epoch": https://momentjs.com/docs/#/parsing/utc/
As you're passing zero, the result is the Unix epoch itself, which is January 1st 1970 at midnight in UTC.
Then you call .format("HH:mm:ss")
to print the hours, minutes and seconds. As moment.utc(0)
is at midnight, the result is 00:00:00
.
If you want to calculate the difference between 2 dates, use the diff
method as explained by Pavlo's answer.