我在字符串“11:56:41,11 / 22/2011”中有这个日期时间格式。
这就是我想要的:
比较两个日期时间字符串,例如。
$date1 = "11:56:41, 11/22/2011";
$date2 = "11:20:41, 11/20/2011";
if($date2 < $date1) {
do something...
} else {
do nothing...
}
我有什么想法可以在perl中实现这个目标吗?
答案 0 :(得分:13)
在将时间转换为Time::Piece
个对象后使用重载比较的另一个解决方案。创建对象可能对于简单的事情来说是过度的,但如果你需要与时俱进,它们会变得非常有用。
use Time::Piece;
my $dateformat = "%H:%M:%S, %m/%d/%Y";
my $date1 = "11:56:41, 11/22/2011";
my $date2 = "11:20:41, 11/20/2011";
$date1 = Time::Piece->strptime($date1, $dateformat);
$date2 = Time::Piece->strptime($date2, $dateformat);
if ($date2 < $date1) {
do something...
} else {
do nothing...
}
答案 1 :(得分:11)
一种有效的方法是将字段重新排序为具有词汇可比性的字段。
sub to_comparable {
my ($date) = @_;
my ($H,$M,$S,$d,$m,$Y) = $date =~ m{^([0-9]{2}):([0-9]{2}):([0-9]{2}), ([0-9]{2})/([0-9]{2})/([0-9]{4})\z}
or die;
return "$Y$m$d$H$M$S";
}
if (to_comparable($date2) lt to_comparable($date1)) {
...
} else {
...
}
答案 2 :(得分:5)
什么,已经4个小时而不是一个DateTime(所有人都欢呼强大的DateTime)答案在眼前?你懈怠,perl订阅者......☻
use DateTime::Format::Strptime qw();
my $p = DateTime::Format::Strptime->new(pattern => '%T, %D', on_error => 'croak',);
my $date1 = $p->parse_datetime('11:56:41, 11/22/2011');
my $date2 = $p->parse_datetime('11:20:41, 11/20/2011');
if($date2 < $date1) {
say "$date2 comes before $date1";
} else {
say "$date2 does not come before $date1";
}
方法parse_datetime
返回DateTime
的实例,其比较运算符和字符串化被重载到DTRT。
答案 3 :(得分:2)
我使用unixtime。 :)
我将两次转换为unixtime然后我只有两个整数进行比较,因此我可以使用运算符&lt;,==,&gt;等
e.g。转换为unixtime如下
my $timestamp = "2014-03-25 12:33:32"; # (We assume localtime)
#
# To split on the space character, it's best to use the regex / /
#
my ($date, $time) = split (/ /, $timestamp);
my ($year, $mon, $mday) = split ('-', $date);
my ($hour, $min, $sec) = split (':', $time);
my $unixtime = timelocal($sec, $min, $hour, $mday, $mon-1, $year);
答案 4 :(得分:1)
将日期时间(在您的情况下,这些是本地日期时间,因为它们没有时区)转换为ISO8601,然后您可以进行常规字符串比较。
要执行转换,您应该从格式中提取六个组件
HH:MM:SS, mm/DD/YYYY
并将它们重新组装成ISO 8601:
YYYY-MM-DDTHH:MM:SS
然后正常的词典比较将起作用。
请参阅http://codepad.org/berle9um
在此重复:
sub my_format_to_iso8601 {
$_[0] =~ /(\d\d):(\d\d):(\d\d), (\d\d)\/(\d\d)\/(\d\d\d\d)/;
return "$6-$4-$5T$1:$2:$3";
}
$date1 = "11:56:41, 11/22/2011";
$date2 = "11:20:41, 11/20/2011";
$d1 = my_format_to_iso8601($date1);
$d2 = my_format_to_iso8601($date2);
print "first is $d1\n";
print "second is $d2\n";
if ($d2 < $d1) {
print "second is earlier\n";
} else {
print "first is earlier\n";
}
<强>附录强>
答案 5 :(得分:1)
在这种情况下,我总是使用Date::Calc
:
use Date::Calc;
my $date1 = "11:56:41, 11/22/2011";
my $date2 = "11:20:41, 11/20/2011";
my @date1arr=split /[^\d]/, $date1 if($date1 =~ m!\d{2}:\d{2}:\d{2}, \d{2}/\d{2}/\d{4}!;
my @date2arr=split /[^\d]/, $date2 if($date2 =~ m!\d{2}:\d{2}:\d{2}, \d{2}/\d{2}/\d{4}!;
my @diff = Delta_DHMS(@date1arr, @date2arr);
my $less;
foreach my $d ( @diff ) { $less = 1 if $d < 0; }
if($less) { ... }