我将DateTime标记保存到我的数据库中:
2015-02-23T16:59:25
我有一个新的日期时间戳,代表当前时间。
2015-02-24T16:59:25
我需要将两者与DateTime进行比较,以检查是否已经过了24小时。
#!/usr/bin/perl
use strict;
use DateTime;
my $longenough;
Testing123();
exit;
sub Testing123{
my $yesterday = DateTime->now;
$yesterday->add( days => -1 );
#This $yesterday time gets saved to my database.
#For question purposes, I'll just pass it along instead of from db.
CheckLapse($yesterday);
if ($longenough eq 'y'){ print qq~24 hours have passed<br />~; }
else{print qq~24 hours have not passed<br />~;}
}
sub CheckLapse{
$yesterday = shift;
my $now = DateTime->now;
# leftovers from many many hours of different attempts from my old bramaged drain
# my $elapse = $now - $yesterday;
# $now->subtract_duration( $yesterday ) ;
# $TimeLapse = $elapse->in_units('seconds'); #Left over from another try
# print "Elapsed time : ".$elapse->in_units('seconds')."m\n";
## I need to compare the two times and pass $longenough y/n back:
if ($TimeLapse >= [24 hours whatever seconds minutes to do calc]){
$longenough = 'y';
}
else {$longenough = 'n';}
return $longenough;
}
exit;
我已经阅读并阅读了cpan DateTime文档并尝试了一切,除了显然,正确的解决方案。 我只是不断收到“无法调用方法”yada yada“没有包或对象引用”的错误。
有人可以在这教育我吗?
答案 0 :(得分:3)
您可以从字符串构造DateTime对象,如下所示:
use DateTime::Format::Strptime qw( );
my $dt_format = DateTiFormat::Strptime->new(
pattern => '%Y-%m-%dT%H:%M:%S',
time_zone => 'local',
on_error => 'croak',
);
my $dt = $dt_format->parse_datetime('2015-02-23T16:59:25');
然后你可以检查它是否像这样24小时:
my $now = DateTime->now( time_zone => $dt->time_zone );
if ($dt->clone->add( hours => 24 ) >= $now) {
# It's been more than 24 hours.
...
}
现在,每次检查24小时是否已经过去,上面做了很多工作。如果重复执行此操作,可以按如下方式使用减少工作负载:
use DateTime::Format::Strptime qw( );
my $dt_format = DateTime::Format::Strptime->new(
pattern => '%Y-%m-%dT%H:%M:%S',
time_zone => 'local',
on_error => 'croak',
);
my $dt = $dt_format->parse_datetime('2015-02-23T16:59:25');
$dt->add( hours => 24 );
my $target_time = $dt->epoch;
然后检查然后简化为
if ($target_time >= time)
# It's been more than 24 hours.
...
}
您可能希望->add( days => 1 )
(下一个日历日的同一时间)而不是->add( hours => 24 )
。
答案 1 :(得分:1)
DateTime
模块庞大而缓慢,是一个完整的工具箱,可用于任何与日期时间相关的工具。 Time::Piece
是一个重量轻得多的核心模块(因此不需要安装)并且完全可以完成这项任务。
以下是使用Time::Piece
use strict;
use warnings;
use 5.010;
use Time::Piece ();
use Time::Seconds 'ONE_DAY';
my ($t1, $t2) = qw/
2015-02-23T16:59:25
2015-02-24T16:59:25
/;
my $diff = delta_time($t1, $t2);
say $diff >= ONE_DAY ? 'over one day' : 'less than one day';
sub delta_time {
my ($t1, $t2) = map Time::Piece->strptime($_, '%Y-%m-%dT%H:%M:%S'), @_;
return $t2 > $t1 ? $t2 - $t1 : $t1 - $t2;
}
<强>输出强>
over one day