Search code examples
perltimeperl-moduleepoch

How to convert dd/mm/yyyy to epoch time in Perl?


I have searched several hours for a formula to convert dd/mm/yyyy format into epoch time but have not found a solution.

I have two dates, after converting from 2 different formats, that are now like this "08011985" and "09302014". I have to convert them to epoch time to get the difference from earliest and latest date, and do something based on the size of the spread.

I can't install any modules and am on 5.8.8.


Solution

  • Here's an example using the Time::Local module, which has always been a core component of Perl 5.

    use strict;
    use warnings;
    
    use Time::Local qw/ timelocal /;
    
    for my $date ( qw/ 08011985 09302014 / ) {
      print epoch_for_mmddyyyy($date), "\n";
    }
    
    sub epoch_for_mmddyyyy {
      my ($m, $d, $y) = unpack 'A2A2A4', shift;
      timelocal(0, 0, 0, $d, $m-1, $y);
    }
    

    output

    491698800
    1412031600