fionbarr has asked for the wisdom of the Perl Monks concerning the following question:

I am retrieving a sql datetime value that looks like:
2012-01-31 00:00:00.000
I am comparing with 'today' with regex's and I'm sure there is a much better way.

Replies are listed 'Best First'.
Re: sql datetime value with today
by Anonymous Monk on Sep 19, 2014 at 19:31 UTC

    If you're retrieving your SQL DATETIME as a string, use something like Time::Piece's strptime or DateTime::Format::Strptime to convert it to a better representation, then use the provided methods to compare.

    use DateTime (); use DateTime::Format::Strptime (); print DateTime::Format::Strptime ->new(pattern => '%Y-%m-%d %H:%M:%S.%3N') ->parse_datetime('2012-01-31 00:00:00.000') ->truncate(to=>'day') ->compare( DateTime->today ); # compare returns 0 if they're equal

    That might seem like a little overkill for what could be done with a simple string comparison of two dates in the same format, but can be very useful once time zones or other DateTime features get involved.

      thanks....
Re: sql datetime value with today
by erix (Prior) on Sep 19, 2014 at 22:36 UTC

    I'm not sure but it may be better / easier / faster / simpler to do the comparison in the SQL:

    Something like http://sqlfiddle.com/#!3/d2910/8/2

    -- fiddle schema (LHS): create table t( d date ); -- fiddle SQL (RHS): insert into t values ( getdate() ) , ( getdate() + 1 ) ; -- t now contains 2 rows select * from t where d = cast(getdate() as date); -- returns only the one row

    (Note that you have to cast the value as getdate returns a timestamp and not a date)

Re: sql datetime value with today
by erix (Prior) on Sep 19, 2014 at 19:07 UTC

    How? What database?

    Where is there a problem?

    How about you spend more then 10 seconds composing your question?

      sql server is the database
      (my $dd = $due_date) =~ s/-//g; $dd =~ /(\d{8})/; $past_due_date = ( $1 < $compare_date ) ? 'yes' : 'no';
      where $dd and $compare_date both = 'yyyyddmm'
Re: sql datetime value with today
by runrig (Abbot) on Sep 19, 2014 at 22:11 UTC
    If you have 2 strings in the same format as what you have, you can just use one of the operators eq,ne,lt,gt,le,ge, or cmp to compare. No need to convert.