There are a couple of APIs suggested on the TC39 site. I tried
@js-temporal/polyfill and have had no issues.
The API provides a few ways to initialize a Temporal Duration. Probably, the most intuitive is:
Did you spot the Sinéad O’Connor reference in that example? If you have a period other than
seven hours and 15 days, then you have access to
seconds and even
nanoseconds, as well as
For many cases, ISO 8601 is more convenient. This is just a string of letters and numbers in
shorthand. An example is
P is just a marker that we are using an ISO 8601 period,
separates units shorter than a day from longer units. The
fifteen days and
7H seven hours. The
T separator is needed since
M to the left of it represents
months, while, to the right, represents minutes. So you can appreciate that if you want to note
down a period of six years, five months, four days, three hours, two minutes and one second, you
can succinctly, write
P6Y5M4DT3H2M1S. There is a
W (week) unit too, though this should not be used together with other units for maximum compatibility.
Back to the previous example, we can initiate the Temporal Duration using an ISO 8601 period thus:
To see a few more Temporal duration methods, we will take a look a track list from Madonna’s True Blue album. If you are not into 1980s music, fear not, this is the last 1980s artist reference in this post.
Here’s our output:
Notice how in the input JSON, our track lengths use ISO 8601 durations. This is convenient as it creates short strings, which are easily serializable as JSON too. We will initialize Temporal Durations using these ISO 8601 strings (like we saw earlier), then see how we can convert them to user-friendly strings for our use case. Finally, we will sum all the tracks lengths using the Temporal API to get a total playing time for the LP (album).
There is a
.toLocaleString() method on Temporal Durations, which
works similarly to the equivalent Temporal Date and Time methods. However, this relies on
Intl.DurationFormat support. That is another proposal which is not yet widely supported, so let’s roll our
own and see some Temporal Duration manipulation methods in the process.
Temporal objects have
seconds fields, which contain those values as numbers (rather than strings). These let us write a
simple function to convert the Temporal Duration objects to string for display:
This takes an input like
PT4M39S and returns
4:39. We pad the seconds so that, for example, four minutes and two seconds gets written
4:02, as would be expected by a user or site visitor. We use this function to convert track lengths
from ISO 8601 strings to the strings we see in the image.
We can easily add durations using the
That creates a new Temporal.Duration object. For years, months and weeks, the intent could be
ambiguous, so you need also to provide an object with a
relativeTo date field as a second argument.
add to work out the total track time using the array reduce method :
accumulator keeps a running total of the duration as we loop
through the members of the array. Each array member is an object with a
length field, the duration of the track, as an ISO 8601 string. We initialize the accumulator with
new Temporal.Duration(), equivalent to zero duration.
You could do this manipulation manually by parsing the durations and converting them to seconds,
summing and then converting the output to human-readable string. That is no way to live your life,
though! More seriously, using the Temporal API Duration object should result in more robust, less
error-prone code which is also cleaner and easier to understand. There is a similar
subtract method as well as absolute, rounding, and negation methods. See the TC39 docs for more details .
We have had an introduction to the Temporal API Duration. In particular, we saw:
- how to initialize a Temporal Duration from an object or ISO 8601 string;
- what an ISO 8601 duration string is; and
- also how you can sum durations using the Temporal API.
Open up the Astro project we referenced from the Rodney Lab GitHub repo to play around .
I hope you found this article useful and am keen to hear how you will use the starter on your own projects as well as possible improvements.
- ISO 8601 can be used to write durations spanning periods shorter or longer than a day. The durations are written as a string of letters and numbers and start with a `P`. When there are units shorter than a day present, these are separated from longer duration units with a `T`. Other letters like `Y`, `M`, `D` or `H`, `M`, `S` represent the units. `M` represents month units when it appears before the `T` and minutes after. For example, `PT5M3S` represents a period of five minutes and three seconds. Meanwhile, `P5Y2MT4H1M` is five years, two months, four hours and one minute.
- To create a new Temporal Duration object from an ISO 8601 string, just pass it as an argument to the `from` method: `const duration = Temporal.Duration.from("P5Y2MT4H1M")` .
- It is possible to sum temporal API durations. However, to avoid ambiguity in summing terms which include years, months or weeks, you need to add an extra `relativeTo` date parameter. There is no need for that for other, shorter durations; here you just call `add` on one duration, providing the second duration as the argument: `totalDuration = durationA.add(durationB)`. That returns a new duration object. When you do need a `relativeTo` date, this is just provided as an object in an additional second argument.
Have you found the post useful? Would you prefer to see posts on another topic instead? Get in touch with ideas for new posts. Also, if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on Astro as well as SvelteKit. Also, subscribe to the newsletter to keep up-to-date with our latest projects.