quinekxi quinekxi - 5 months ago 9
Perl Question

How to compare string date time in perl?

I have this date time format in string "11:56:41, 11/22/2011".

Here's what I want:

Compare two date time strings like.

$date1 = "11:56:41, 11/22/2011";
$date2 = "11:20:41, 11/20/2011";
if($date2 < $date1) {
do something...
} else {
do nothing...
}


Any ideas how could i achieve this in perl?

Answer

An efficient method is to reorder the fields to something lexically comparable.

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 {
   ...
}