0

我想检查当前时间是否小于、等于或大于 20:00(例如)。我怎么能用 Perl 做到这一点?

谢谢。

4

4 回答 4

3

查看localtime功能。

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

更新:感谢 Dave Cross 指出由于两次调用localtime().

于 2013-02-07T13:26:42.803 回答
2

目前还不清楚你在问什么,但也许是这样的。

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";
}
于 2013-02-07T13:59:00.667 回答
0

实际上正确的“如果”条件会有所不同,如果小时大于分钟,您不需要检查分钟是否更大(我还固定了标志的方向:)

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";    
}
于 2013-12-05T13:35:12.633 回答
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";
}

对于这种情况可能有点矫枉过正,但 DateTime 的灵活性允许您轻松实现其他逻辑(工作日/周末的不同截止时间,小时和分钟的截止时间),而无需深入研究 if-then-else 逻辑。

于 2013-02-08T19:53:50.590 回答