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

Hi

I was wondering where would I begin if I wanted to compare time from a string value to the computers real time.

For example, I have this script that inputs data inside a database. I want it to only insert if its not pass a given time.

So I have a string value that determines the time that the "store closes". $store_close = "7:05 PM"

So the script should only insert the data if the store is open, once the local computer time is pass 7:05 PM then it should not insert.
My train of thought... my $store_close = "7:05 PM"; my $t = time(); #need some conversion where I can convert 7:05 PM to the time in numbe +rs and then do if ($time > $my_converted_time) { print "Store Closed! Can not insert record!"; }
I tried looking up some time modules on CPAN, but not sure which ones I should be using. I'm more of a PHP person so still very new to Perl. Sorry if this is a stupid question...but I will give it a go. Any help is welcome :)

Lester </c>

Replies are listed 'Best First'.
Re: Comparing a string value's time with the computers time
by GhodMode (Pilgrim) on Aug 03, 2006 at 04:33 UTC
    No modules needed :) ... Try this ...
    use strict; use warnings; use POSIX qw{ strftime }; my $db_time = "7:05"; my $current_hour = strftime( "%H", localtime() ); my $current_minute = strftime( "%M", localtime() ); my ($db_hour, $db_minute) = split( /:/, $db_time ); if ( $db_hour > $current_hour ) { print "It is still open.\n"; } elsif ( $db_hour < $current_hour ) { print "It is closed already.\n"; } elsif ( $db_minute > $current_minute ) { print "It is still open\n"; } elsif ( $db_minute < $current_minute ) { print "It is closed already.\n"; } else { print "Hurry... It is closing RIGHT NOW!!!"; }
    --
    -- Ghodmode
    
    Blessed is he who has found his work; let him ask no other blessedness.
    -- Thomas Carlyle

      GhodMode, there is a subtle race-condition in your example. Since you are calling localtime twice, it could potentially return two different values. For instance, say you ran the code right as the clock struck ten:

      my $current_hour = strftime( "%H", localtime() ); # say it's 9:59, so +"9" is returned. # ... your process is switched off the processor... my $current_minute = strftime( "%M", localtime() ); # now it's 10:00, +so "00" is returned.
      Now your code would act as if it's 9:00pm, when in fact it's 10:00pm. Not trying to nit-pick, but I just couldn't help noticing... ;-)

      If it were me, I would keep the "closing time" in 24-hour format (I realize the OP doesn't in his/her example) and completely forgo the use of strftime:

      #my $store_close = "7:05 PM"; my $store_close = "19:05"; my ($close_hour, $close_minute) = split( /:/, $store_close ); my ($current_minute, $current_hour) = (localtime)[1,2];

    A reply falls below the community's threshold of quality. You may see it by logging in.