How can i compare two dates in the format using Perl:
"dd mon yyyy hh:mm:ss GMT"
e.g.: 12 May 2013 10:10:20 GMT
I cannot install any external Perl modules. Please advice.
How can i compare two dates in the format using Perl:
"dd mon yyyy hh:mm:ss GMT"
e.g.: 12 May 2013 10:10:20 GMT
I cannot install any external Perl modules. Please advice.
If you have Perl v5.9.5 or newer, you can use Time::Piece core module. Here's a simple demonstration of relevant operations
Convert the dates from string to Time::Piece object
my $date = "12 May 2013 10:10:20 GMT";
my $tp1 = Time::Piece->strptime($date, "%d %B %Y %T %Z");
my $tp2 = ...
Find the difference between the 2 time
my $diff = $tp2 - $tp1;
which gives you a Time::Seconds object.
Finally, display the difference in units of seconds (or something else).
print $diff->seconds;
Or you could just compare the two directly (thanks stevenl)
$tp2 > $tp1
References:
Time::Piece->strptime$tp->strftime
aAbBcdHIjmMpSUwWxXyYZ% are safe if you're using non-Unix system (for example, Window's Perl doesn't support the %e specifier). Convert the dates to the format yyyymmddhhmmss (e.g. 20130512101020) and compare as strings. Handling the time zones might get tricky without modules, though.
One of the most popular date modules is DateTime. It has a FAQ which may help you get started.
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) < to_comparable($date1)) {
...
} else {
...
}