我的日期时间值格式为" 2016年7月1日星期五05:21:23",我该怎么比较呢?
我需要像if($date1<$date2) { print "do something"! }
请帮助找到答案!
答案 0 :(得分:3)
您可以使用DateTime::Format::Strptime
将字符串解析为支持比较的Datetime
个对象:
use strict;
use warnings;
use feature 'say';
use DateTime::Format::Strptime;
my $strp = DateTime::Format::Strptime->new(pattern => '%a %b %d %H:%M:%S %Y');
my $dt1 = $strp->parse_datetime("Fri Jul 1 05:21:23 2016");
my $dt2 = $strp->parse_datetime("Sat Jul 2 05:21:23 2016");
if ($dt1 < $dt2) { # or use DateTime->compare()
say '$dt1 < $dt2';
}
elsif ($dt1 == $dt2) {
say '$dt1 == $dt2';
}
else {
say '$dt1 > $dt2';
}
答案 1 :(得分:2)
使用Time::Piece将字符串转换为可以直接比较的对象。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Time::Piece;
my $date1 = 'Fri Jul 1 05:21:23 2016';
my $date2 = 'Thu Jun 30 12:00:00 2016';
my $date_format = '%a %b %d %H:%M:%S %Y';
my $tp1 = Time::Piece->strptime($date1, $date_format);
my $tp2 = Time::Piece->strptime($date2, $date_format);
if ($tp1 < $tp2) {
say "$date1 is before $date2";
} elsif ($tp1 > $tp2) {
say "$date1 is after $date2";
} else {
say "$date1 is the same as $date2";
}