0

I want to check if current time is small , equal or great of 20:00 ( for example). How i can do it with Perl?

Thanks.

VladB
  • 69
  • 4
  • 6
  • 2
    See http://stackoverflow.com/questions/8221841/how-to-compare-string-date-time-in-perl & http://www.perlmonks.org/?node_id=233746 – Andy Thompson Feb 07 '13 at 13:26

4 Answers4

3

Check out the localtime function.

use warnings;
use strict;

my $after_time = "13:32";

my @time = localtime(time);    

if ($after_time =~ /(\d+):(\d+)/ and
    $time[2] >= $1 and
    $time[1] >= $2
)
{
    print "It is after $after_time";    
}

Update: Thanks, Dave Cross, for pointing out that the original code was flawed due to two calls to localtime().

  • 4
    Two calls to `localtime` mean that there's a tiny possibility that time could click past an hour inbetween them. That would surely confuse the logic here. – Dave Cross Feb 07 '13 at 13:55
  • Indeed; better is to my @t = localtime; then you can compare $t[1] and $t[2] directly. – LeoNerd Feb 07 '13 at 21:08
2

It's not exactly clear what you're asking, but perhaps something like this.

use Time::Piece;

my $hour = localtime->hour;

if ($hour < 20) {
  say "It's before 20:00";
} elsif {$hour > 20) {
  say "It's after 20:00";
} else {
  say "It's 20:00";
}
Dave Cross
  • 68,119
  • 3
  • 51
  • 97
0
my $now = DateTime->now(time_zone => 'local');
my $cutoff = $now->clone->truncate( to => 'day' )->set(hour => 20);

if ($now < $cutoff) {
  say "It's before 20:00";
} elsif ($now > $cutoff) {
  say "It's after 20:00";
} else {
  say "It's exactly 20:00";
}

It may be a little overkill for this situation, but the flexibility of DateTime allows you to easily implement other logic (different cutoffs weekday/weekend, cutoff at hour and minute) without needing to delve too much into the if-then-else logic.

Oesor
  • 6,632
  • 2
  • 29
  • 56
0

Actually the correct "if" condition would be somewhat different, you don't need to check if minutes are greater if the hour is greater than the minutes(I also fixed the direction of the signs :)

use warnings;
use strict;

my $after_time = "13:32";

my @time = localtime(time);    

if ( $after_time =~ /(\d+):(\d+)/
    and (( $time[2] > $1 ) || ( $time[2] == $1 and $time[1] >= $2 ))
) {
    print "It is after $after_time";    
}
Shantanu Bhadoria
  • 14,202
  • 1
  • 12
  • 9