Handrolling ISO8601 Duration Support for Go

submited by
Style Pass
2025-07-27 22:00:12

I wrote my own ISO8601 duration parsing library because the common ones sucked. ISO8601 durations are defined as P[nn]Y[nn]M[nn]DT[nn]H[nn]M[nn]S or P[nn]W.

I’m currently working on a project that requires interacting with the api of a german public transport provider, specifically vbb. To abstract this I wrote go-hafas, however, all fields that include duration are serialized to something along the lines of PT3M, for instance:

There is no ISO8601 support in either time.Parse (there is support for an ISO8601 subset: time.RFC3339, just not for a duration) or time.DurationParse, which only accepts “custom” duration strings someone at google came up with I guess

time.Duration is only backed internally by a int64, this doesn’t mean it can’t contain the ISO8601 duration spec, just fun to know

So I went looking for a library, which left me dumbfounded, because none of them supported my obvious use case (converting a ISO8601 duration to time.Duration) and some weren’t even spec compliant (see next chapter):

Leave a Comment
Related Posts