Search code examples
perldatetimedate-arithmetic

Time difference in seconds


In a Perl program I have a variable containing date / time in this format:

Feb 3 12:03:20  

I need to determine if that date is more than x seconds old (based on current time), even if this occurs over midnight (e.g. Feb 3 23:59:00 with current time = Feb 4 00:00:30).

The perl date / time information I've found is mind-boggling. Near as I can tell I need to use Date::Calc, but I am not finding a seconds-delta. Thanks :)


Solution

  • In perl, there is always more than one way to do something. Here's one which uses only a module that comes standard with Perl:

    #! perl -w
    
    use strict;
    use Time::Local;
    
    my $d1 = "Feb 3 12:03:20";
    my $d2 = "Feb 4 00:00:30";
    
    # Your date formats don't include the year, so
    # figure out some kind of default.
    use constant Year => 2012;
    
    
    # Convert your date strings to Unix/perl style time in seconds
    # The main problems you have here are:
    # * parsing the date formats
    # * converting the month string to a number from 1 to 11
    sub convert
    {
        my $dstring = shift;
    
        my %m = ( 'Jan' => 0, 'Feb' => 1, 'Mar' => 2, 'Apr' => 3,
                'May' => 4, 'Jun' => 5, 'Jul' => 6, 'Aug' => 7,
                'Sep' => 8, 'Oct' => 9, 'Nov' => 10, 'Dec' => 11 );
    
        if ($dstring =~ /(\S+)\s+(\d+)\s+(\d{2}):(\d{2}):(\d{2})/)
        {
            my ($month, $day, $h, $m, $s) = ($1, $2, $3, $4, $5);
            my $mnumber = $m{$month}; # production code should handle errors here
    
            timelocal( $s, $m, $h, $day, $mnumber, Year - 1900 );
        }
        else
        {
            die "Format not recognized: ", $dstring, "\n";
        }
    }
    
    my $t1 = convert($d1);
    my $t2 = convert($d2);
    
    print "Diff (seconds) = ", $t2 - $t1, "\n";
    

    To make this really production-ready, it needs better handling of the year (for example, what happens when the start date is in December and end date in January?) and better error handling (for example, what happens if the 3-char month abbreviation is mispelled?).