use strict; sub prepareFormat { my $format = shift(); my ($i, @order) = 0; $format =~ s/([YMDhms]+)(\?)?/ $order[$i++] = substr($1,0,1); '('. +('\d' x length($1))."$2)"/ge; $format = qr/^(?:$format)$/; return [$format, \@order]; } sub parseDate { my ($format, $date) = @_; my @data = ($date =~ $format->[0]) or return; my %result; for(my $i = 0; $i <= $#data; $i++) { $result{$format->[1]->[$i]} ||= $data[$i]; } return map $result{$_}, qw(Y M D h m s); } #my $format = prepareFormat ('YYYY/MM/DD'); #my $format = prepareFormat ('YYYY-DD-MM|YYYY-DD-M|YYYY-D-MM|YYYY-D-M' +); #my $format = prepareFormat ('YYYY-DD?-MM?'); #my $format = prepareFormat ('YYYY-DD?-MM? hh?:mm?'); #my $format = prepareFormat ('YYYY-DD?-MM? hh?:mm?(?::ss?)?'); my $format = prepareFormat ('YYYY-DD?-MM?(?: hh?:mm?(?::ss?)?)?'); while (<>) { chomp; my ($year, $month, $day, $hour, $min, $sec) = parseDate($format, $ +_) or print "\tNot in the right format!\n" and next; print "Year: $year, Month: $month, Day: $day, Hour: $hour, Min: $m +in, Sec: $sec\n"; }

The prepareFormat() returns a reference to an array containing the regexp and the mapping between the capturing parenthesis and the parts of the date, the parseDate() uses this structure to match the date and extract the data. It then returns (year,month,day,hour,min,sec).

As you can see from the examples you may accept&parse several different datetime formats at once.

Jenda
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
   -- Rick Osborne

Edit by castaway: Closed small tag in signature


In reply to Re: date format string -> Reg Ex solution by Jenda
in thread date format string -> Reg Ex solution by markjugg

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.