1827835 Members
2108 Online
109969 Solutions
New Discussion

date comparision + perl

 
network_4
Advisor

date comparision + perl

Hi,

Please let me know how to compare dates in perl. Let say i have one date as 2/11/2005 2:30AM and other one is 2/11/2005 2:00AM then how i can compare then which is earlier in perl
4 REPLIES 4
Peter Godron
Honored Contributor

Re: date comparision + perl

Hi,
please see this perl article:
http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.11.html

lots of others if you search a bit

Or you could convert date to epoch and then compare.

Please also read:
http://forums1.itrc.hp.com/service/forums/helptips.do?#33 on how to reward any useful answers given to your questions.

So far you have awarded points to only ONE of 42 answers !
Steven E. Protter
Exalted Contributor

Re: date comparision + perl

Shalom,

Lots of good date functionality here.

perl
http://hpux.ws/merijn/caljd-2.2.pl

shell
http://hpux.ws/merijn/caljd-2.25.sh

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Peter Godron
Honored Contributor

Re: date comparision + perl

Hi (again),
for the epoch version of the solution, please see:
http://www.unix.org.ua/orelly/perl/cookbook/ch03_03.htm

Code and explanation is provided on the link.
Ralph Grothe
Honored Contributor

Re: date comparision + perl

Like the others already have posted,
you merely need to transform your date string
into Unix epoch seconds and compare which of the two is smaller.
The standard Perl module Time::Local does the epoch secs conversion.
The only nasty part is the conversion from string into what timelocal() expects.

Here's one way:


#!/usr/bin/perl

use strict;
use Time::Local;

my @t = ('2/11/2005 2:30AM', '2/11/2005 2:00AM');

printf "%s comes before %s\n", (normalize_date($t[0]) < normalize_date($t[1])) ?
@t : reverse @t;

sub normalize_date {
my ($str) = @_;
my ($date, $time) = split /\s+/, $str;
my ($d, $m, $Y) = split q{/}, $date;
my ($H, $M, $PM) = $time =~ /(\d{1,2}):(\d{1,2})(?:AM|(PM))/i;
$H += 12 if $PM;
timelocal(0, $M, $H, $d, --$m, $Y-1900);
}
Madness, thy name is system administration