VladB
VladB

Reputation: 69

Compare time with Perl

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.

Upvotes: 0

Views: 5956

Answers (4)

Shantanu Bhadoria
Shantanu Bhadoria

Reputation: 14510

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";    
}

Upvotes: 0

Oesor
Oesor

Reputation: 6642

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.

Upvotes: 0

user1919238
user1919238

Reputation:

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().

Upvotes: 3

Dave Cross
Dave Cross

Reputation: 69244

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";
}

Upvotes: 2

Related Questions