Brandon
Brandon

Reputation: 910

Comparing times in perl without using modules

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".

Upvotes: 0

Views: 1475

Answers (4)

Alexandr Ciornii
Alexandr Ciornii

Reputation: 7394

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.

Upvotes: 0

mob
mob

Reputation: 118605

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;

Upvotes: 0

Sam Choukri
Sam Choukri

Reputation: 1904

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|;

Upvotes: 0

Alnitak
Alnitak

Reputation: 339796

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.

Upvotes: 5

Related Questions