Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Parse ISO 8601 date/times

by tye (Sage)
on Nov 05, 2012 at 17:08 UTC ( #1002366=CUFP: print w/replies, xml ) Need Help??

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        

Replies are listed 'Best First'.
Re: Parse ISO 8601 date/times
by grizzley (Chaplain) on Nov 07, 2012 at 09:41 UTC
    \d is equivalent of [0-9] Update: Stupid UTF or other sh*t in choroba's reply below ruined my brilliant hint. Must search for my XP points somewhere else :P


      I'm guessing he used [0-9] for visual symmetry with [0-2], [0-3], et. al. I was going to suggest that it would be easier to read, but when I converted a little bit from this:

      && $part !~ m{ # Time or partial time (or period): ^(?:|P)T [012][0-9] (?:| :?[0-5][0-9] (?:| :?[0-5][0-9] ) ) (?:| [.,][0-9]+ )$ }x

      to this:

      && $part !~ m{ # Time or partial time (or period): ^(?:|P)T [012]\d (?:| :?[0-5]\d (?:| :?[0-5]\d ) ) (?:| [.,]\d+ )$ }x

      I found that the better 'visual balance' of [0-9] was counterbalanced by the square brackets, which are a little too similar to vertical bars for my eyes. After looking at them both, I don't really have a preference--Perhaps if I had a better font...


      When your only tool is a hammer, all problems look like your thumb.

        I agree. [0-9] is visually better in this case.
      Oh really?
      $d = chr(2413); print $d =~ $_, "\n" for qr/\d/, qr/[0-9]/;
      لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

        Yeah, I just don't ever use \d except for one-liners any more. \d now means something that I just never want: numerals of any kind, from any writing system. This despite Perl only knowing how to treat one of the two dozenish types of numerals as numeric. I think drastically changing the definition of \d when Unicode came along was a mistake (a separate way of saying "any numeral" should have been used).

        Luckily, the somewhat longer [0-9] has some visual advantages. So the worst problem is all of the old scripts that are now broken in ways that will often not matter (but that I can see even causing security problems in rare cases).

        - tye        

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://1002366]
Approved by Corion
Front-paged by Arunbear
and snow settles gently...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2018-06-19 22:43 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (115 votes). Check out past polls.