Take the 2-minute tour ×

I am trying to compare two timestamps to see which one is the latest one, this would be easy if I could use the DateTime module, but unfortunately I do not have permissions to install any modules on the servers and therefore I am restricted to only native Perl commands.

The times are in the form "MM/DD/YYYY hh:mm:ss".

share|improve this question
There is no need for special permissions to install modules. They can be installed to any directory. –  ikegami Apr 19 '11 at 21:46
Note that if the times are in local time and your local time zone has DST, it's impossible to sort the times perfectly from the information you gave. On one day a year, 1:30:00 comes both before and after 1:15:00. –  ikegami Apr 19 '11 at 21:49
Yes, even you can use CPAN –  Tanktalus Apr 19 '11 at 22:04
add comment

4 Answers

up vote 5 down vote accepted

If you first convert the times into YYYY/MM/dd hh:mm:ss format using the code below:

my ($date, $time) = split(/\s+/, $val);
my ($m, $d, $y) = split(/\//, $date);
$val = sprintf("%04d/%02d/%02d %s", $y, $m, $d, $time);

You can then just use a standard lexical comparison on the dates.

share|improve this answer
add comment

You can use a regexp to reformat the date to "YYYY/MM/DD hh:mm:ss" format so that you can compare two dates directly.

$date =~ s|^(\d{2})/(\d{2})/(\d{4})|$3/$1/$2|;
share|improve this answer
add comment

The only part of the string that is out of order for a lexical sort is the YYYY part, so you can compare that part separately.

# MM/DD/YYYY hh:mm:ss
# 0123456789T12345678
@sorted_dates = sort { substr($a,6,4) cmp substr($b,6,4) || $a cmp $b } @dates;
share|improve this answer
add comment

Perl includes Time::Piece and Time::Local modules. Or you can create executable with PAR::Packer that will include DateTime and copy it into server.

Of course, converting to "YYYY-MM-DD hh:mm:ss" format is easiest if any other features are not needed.

share|improve this answer
add comment

Your Answer


