http://www.perlmonks.org?node_id=1002366

Recently I was faced with an upgrade of an XML RPC module causing problems. Turns out it decided to get strict about what it would accept as an ISO-8601 date/time but had some serious shortcomings when it came to even understanding the basics of ISO-8601 (probably due to focusing just on the XML RPC standard, which only barely mentions ISO-8601 and follows that by giving an example which doesn't actually conform to ISO-8601).

Before I fully understood that the prior version just didn't care about invalid values (so we should stick with that posture for reasons of compatibility), I quickly coded up a much more complete understanding of ISO-8601. This should soon end up in a bug report or just a new release for the module in question.

In the mean time, it might be useful to some people. There are some ISO-8601 modules on CPAN already. The first appears to not support parsing such strings at all (just constructing them). Glancing at the source code for the third showed basic failures like not understanding that most of the punctuation is optional. But DateTime::Format::ISO8601 might well parse ISO-8601 correctly.

Here is my much simpler code that just validates ISO-8601 format. Note that it doesn't get strict about requiring punctuation to be either "all present" or "all missing" so that it will accept the date-time given as an example in the XML RPC spec (despite it not strictly conforming to ISO-8601).

sub assert_iso8601 { my( $value ) = @_; my $dec = '[0-9]+ (?:| [.,][0-9]+ )'; # Should disallow m{^[0-9]{4}[01][0-9]$} (hyphen required) my $remain = $value; $remain =~ s{^R[0-9]*/}{}; my @parts = split m{/|--}, $remain, -1; die "Malformed datetime: Too many / or -- delimiters ($value).\n"; if 2 < @parts; for my $part ( @parts ) { if( $part !~ m{ # Combined date-time (time can be partial): ^(?:|P) [0-9]{4}-? # Leading "P" for "Period" (durati +on) (?: [01][0-9]-?[0-3][0-9] | W[0-5][0-9]-?[1-7] ) T[012][0-9] (?:| :?[0-5][0-9] (?:| :?[0-5][0-9] ) ) (?:| [.,][0-9]+ ) (?:| Z | [-+][0-2][0-9] (?:| :?[0-5][0-9] ) )$ }x && $part !~ m{ # Date or partial date (or period): ^(?:|P) [0-9]{4} (?:| -?[01][0-9] (?:| -?[0-3][0-9] ) +)$ }x && $part !~ m{ # Time or partial time (or period): ^(?:|P)T [012][0-9] (?:| :?[0-5][0-9] (?:| :?[0-5][0-9 +] ) ) (?:| [.,][0-9]+ )$ }x && $part !~ m{ # Duration: ^P $dec W$ # in weeks | ^P (?= [0-9] ) # in any of YMD HMS (?! [^.,]*[.,][0-9]+[^.,0-9]+[.,0-9] ) # .\d must be +last (?:| $dec Y )(?:| $dec M )(?:| $dec D ) (?:| T (?= [0-9] ) (?:| $dec H )(?:| $dec M )(?:| $dec S ) )$ }x ) { die "Malformed datetime ($value).\n" if $value eq $part; die "Malformed datetime ($part), part of ($value).\n"; } } return; }

- tye