Perl FAQ 4.11: How can I compare two date strings?

Perl FAQ 4.11

How can I compare two date strings?

If the dates are in an easily parsed, predetermined format, then you can break them up into their component parts and call &timelocal from the distributed perl library. If the date strings are in arbitrary formats, however, it's probably easier to use the getdate program from the Cnews distribution, since it accepts a wide variety of dates. Note that in either case the return values you will really be comparing will be the total time in seconds as returned by time(). Here's a getdate function for perl that's not very efficient; you can do better than this by sending it many dates at once or modifying getdate to behave better on a pipe. Beware the hardcoded pathname.

    sub getdate {
	local($_) = shift;
	s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
	    # getdate has broken timezone sign reversal!
	$_ = `/usr/local/lib/news/newsbin/getdate '$_'`;

You can also get the GetDate extension module that's actually the C code linked into perl from wherever fine Perl extensions are given away. It's about 50x faster. If you can't find it elsewhere, I usually keep a copy on for ftp, since I (Tom) ported it.

Richard Ohnemus <Rick_Ohnemus@Sterling.COM> actually has a getdate.y for use with the Perl yacc (see question 3.3 "Is there a yacc for Perl?").

You might also consider using these:        - print dates how you want with the sysv +FORMAT method 
date.shar      - routines to manipulate and calculate dates
ftp-chat2.shar - updated version of ftpget. includes library and demo 
getdate.shar   - returns number of seconds since epoch for any given
ptime.shar     - print dates how you want with the sysv +FORMAT method 

You probably want 'getdate.shar'... these and other files can be ftp'd from the /pub/perl/scripts directory on See the README file in the /pub/perl directory for time and the European mirror site details.

Other resources at this site: