How to convert dd / mm / yyyy to epoch in Perl?
I've searched for hours for a formula to convert dd / mm / yyyy format to epoch but couldn't find a solution.
I have two dates, after converting from two different formats, which now look like "08011985" and "09302014". I have to convert them to epoch to get the difference from the earliest and latest date, and do something based on the spread size.
I cannot install any modules on 5.8.8 either.
+3
source to share
2 answers
Here's an example using a module Time::Local
that 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
0
source to share
The built-in module Time :: Local provides inverse time localtime and gmtime, timelocal and timegm. They take dates and times and return the era.
perlfaq4 covers such questions.
+5
source to share