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

I have some dates I need to compare. One comes from a database query and the other comes from a data calculation at script execution.

# calculate data on run time to even previous hour my $dt = POSIX::strftime("%Y-%m-%d", localtime( shift( @_ ) || time ) +); my $hr = POSIX::strftime("%H", localtime( shift( @_ ) || time ) ); my $bhr = $hr - 1; my $bdt = "$dt $bhr:00:00"; # this one comes from the DB but it looks like this my $db_date = "2015-04-08 12:42:13"; # this is what I want to do if ($db_date <= $bdt) { # process }

But, obviously, that will not work:

Argument "2015-04-09 12:00:00" isn't numeric in numeric le (<=) at ./c +hk_notify_threshold.pl line 57. Argument "2015-04-09..." isn't numeric in numeric le (<=) at ./chk_not +ify_threshold.pl line 57.

How would I go about comparing these dates? Are there functions that will turn this string into a number?

Replies are listed 'Best First'.
Re: Compare Dates
by jeffa (Bishop) on Apr 09, 2015 at 20:15 UTC

    This is where i like to use Time::Piece (Time::Seconds contains useful constants)

    use strict; use warnings; use Time::Piece; use Time::Seconds; my $date_from_db = some_magic_function(); my $one_hour_ago = localtime( shift( @_ ) || time ) - ONE_HOUR; my $db_date = Time::Piece->strptime( $date_from_db, '%Y-%m-%d %H:%M:%S +' ); if ($db_date >= $one_hour_ago) { # process }

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Compare Dates
by runrig (Abbot) on Apr 09, 2015 at 18:31 UTC
    if ($db_date <= $bdt) { # process }
    "<=" is for numeric comparison, you want the 'le' operator for string comparison:
    if ($db_date le $bdt) { # process }

        If the dates are in some form of numeric 'year month day hour minute second', then check all fields are 0 padded, and a gt/lt/eq compare is perfectly valid and simple to grok what's going on. Its only when you get to the insanity of YYYY DD MM formats, that things go pear shaped...

        http://www.w3.org/TR/NOTE-datetime

        Cheers,
        R.

        Pereant, qui ante nos nostra dixerunt!
        The OP doesn't use Time::Piece.
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Compare Dates
by pme (Monsignor) on Apr 09, 2015 at 18:29 UTC