in reply to Converting MySQL datetime values to DateTime objects

One thing I found helpful with PM is a simple regex that matches both a MySQL timestamp (which is a digit string) and MySQL datetime fields (which contains punctuation):

my( $yr, $mo, $day, $hr, $min, $sec )= $when =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
PerlMonks used to have separate code for dealing with timestamps vs. datetime fields.

Then you can construct nearly any date/time object you wish from the individual values.

Update: Gah! Serves me right for not looking at the code in question. The real/working code is more like:

my( $cc, $yr, $mo, $day, $hr, $min, $sec )= $when =~ /(\d\d)/g; $yr += $cc*100;
Sorry!

                - tye

Replies are listed 'Best First'.
Re: Re: Converting MySQL datetime values to DateTime objects (regex)
by LanceDeeply (Chaplain) on Jul 14, 2003 at 20:46 UTC
    what am i doing wrong here? i've tried it w/ and w/o the parens around the regexp.
    use strict; use warnings; my $when = '2003-07-14 21:39:26.357'; my ( $yr, $mo, $day, $hr, $min, $sec ) = ( $when =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ ); print "( $yr, $mo, $day, $hr, $min, $sec )\n"; __DATA__ Use of uninitialized value in concatenation (.) or string at C:\dev\sc +ripts\reg.pl line 6. Use of uninitialized value in concatenation (.) or string at C:\dev\sc +ripts\reg.pl line 6. Use of uninitialized value in concatenation (.) or string at C:\dev\sc +ripts\reg.pl line 6. Use of uninitialized value in concatenation (.) or string at C:\dev\sc +ripts\reg.pl line 6. Use of uninitialized value in concatenation (.) or string at C:\dev\sc +ripts\reg.pl line 6. Use of uninitialized value in concatenation (.) or string at C:\dev\sc +ripts\reg.pl line 6. ( , , , , , )
    can somebody help a (clueless) brother out?
    Update:
    cool cool cool- never knew you could return an array from a regexp. here's another way too:
    my ( $yr, $mo, $day, $hr, $min, $sec ) = ( $when =~ /(\d{4})\D*(\d\d)\D*(\d\d)\D*(\d\d)\D*(\d\d)\D*(\d\d)/ );
      my $when = '2003-07-14 21:39:26.357'; my ( $yr, $mo, $day, $hr, $min, $sec ) = ( $when =~ /(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ );
      You have to match all of the punctuation in your source string. E.g., to match
      my $when = '2003-07';
      you would use
      my ($yr,$mo) = $when =~ /^(\d\d\d\d)-(\d\d)/; ^
      Fixing the complete regex is a variation on this theme.