There are many ways to represent the same duration: for example, "1 minute and 30 seconds" and "90 seconds" are equivalent. However, depending on the context, one representation may be more appropriate than the other. Therefore, generally, the Duration
object preserves the input values as much as possible, so that when you format it, it will be displayed as you expect.
Each component of a duration has its optimal range; hours should be from 0 to 23, minutes from 0 to 59, and so on. When a component overflows its optimal range, the excess may be "carried" into the next larger component. To carry over, we need to answer the question of "how many X are in a Y?", which is a complicated question for calendar units, so in this case a calendar is needed. Also note that by default, days
are directly carried into months
; the weeks unit is only carried into if explicitly requested. If we carry as much as possible, the eventual result where all components are within their optimal range is called a "balanced" duration. Unbalanced durations usually come in the "top-heavy" form, where the largest unit is unbalanced (e.g., "27 hours and 30 minutes"); other forms, such as "23 hours and 270 minutes", are rarely seen.
The round()
method always balances the duration into the "top-heavy" form, up to the largestUnit
option. With a manual largestUnit
option that's large enough, you can fully balance the duration. Similarly, the add()
and subtract()
methods balance the result duration to the largest unit of the input durations.
Note that because the ISO 8601 duration format represents subsecond components as one single fraction number, it is not possible to preserve unbalanced subsecond components during serialization using the default format. For example, "1000 milliseconds" is serialized as "PT1S"
, and then deserialized as "1 second". If you need to preserve the subsecond components' magnitudes, you need to manually serialize it as a JSON object instead (because by default the toJSON()
method serializes the duration in the ISO 8601 format).