Dates and times are a lot more complicated than we normally realize. This episodes explains durations.
You can specify a duration directly and it’s very simple now that you know how the date and time portion works. Just like how a capital letter T is used to signal the beginning of a time, a duration uses a capital letter P. The P stands for period. And there are two ways you can express a duration.
In the first method, you can include numeric values for a number of years, months, days, hours, minutes, and seconds just like how you would specify a date or time. But instead of a fixed number of digits, this form of a duration places another capital letter after each field. You can leave out fields if they’re zero or if you just don’t need them.
After the years, place a capital Y.
After the months, place a capital M.
After the days, place a capital D.
After the hours, place a capital H.
After the minutes, place a capital M.
And after the seconds, place a capital S.
You can instead refer to a duration of weeks and then use a capital letter W. You can’t combine weeks with the other fields though. So if you’re using weeks, then you can only use weeks.
Notice how both months and minutes both use a capital M? That’s okay because you still need the capital letter T to be placed before any time fields.
Using this form of a duration, if you want to express 10 hours and 30 minutes, then the proper way to do this is by writing:
What if you want a duration of 15 months, 1 day, and 12 hours? This is an interesting example because it shows a unique feature of durations that isn’t allowed in the normal DateTime representation. You’re allowed to exceed the normal range of fields in a duration. You can represent 15 months, 1 day, and 12 hours in a few different ways.
You can first convert 15 months into years and months like this:
Or you can just use the months as-is even though it goes beyond 12 like this:
And you can still make use of fractional values at any point. Once you use fractional values though, there can be no more fields. You can combine the 12 hours into half a day like this:
The second form of expressing a duration uses the representation of a DateTime. Using what I just explained about the extra capital letters, you can still use all the date and time formatting you already know to represent a duration by just placing a capital P before it. So you can also represent 10 hours and 30 minutes like this: