Converting Epoch seconds into a readable date.


The Epoch is a very useful feature of Perl, and provides an easily storable date string, in a format that allows date related manipulation to be handled in a simple manner.

The drawback to epoch however, is although it is easy to manipulate, trying to understand what the string means can be a real pig for a beginner.

The first of the programs below is a simple command line perl program which either takes the epoch seconds as a command line argument, or defaults to an existing value stored within the program. After entering the program and saving it as say, convert_epoch1.pl, the program would be run by typing the following at the command line:

./convert_epoch1.pl

or

./convert_epoch1.pl

#!/usr/bin/perl -w
use strict;
my $EPOCH;
$EPOCH=shift(@ARGV) || 991231995;


sub convert_epoch($EPOCH_SECS){
my $EPOCH_SECS=shift;
print "Epoch seconds: ",$EPOCH_SECS;
print "\nDate: ",scalar(localtime($EPOCH_SECS)),"\n";
}#endsub

&convert_epoch($EPOCH);


#!/usr/bin/perl -w
use strict;
my $EPOCH;
$EPOCH = shift(@ARGV) || 991231995;

sub epoch_conversion($EPOCH_SECS)
{
my $EPOCH_SECS = shift;
my ($seconds,$minutes,$hours,$day_of_month,$month,$year,$wday,$yday,$isdst);
print "Epoch seconds: ",$EPOCH_SECS;
print "\nDate returned from passing Epoch seconds to localtime: ";
print scalar(localtime($EPOCH_SECS));
($seconds,$minutes,$hours,$day_of_month,$month,$year,$wday,$yday,$isdst)=localtime($EPOCH_SECS);
print "\n\nSeconds: ",$seconds;
print "\nMinutes: ",$minutes;
print "\nHours: ",$hours;
print "\nDay of month: ",$day_of_month;
print "\nMonth (where 0 = January): ",$month;
print "\nYear (since 1900): ",$year;
print "\nDay of week: ",$wday;
print "\nDay of year: ",$yday;
print "\nDaylight savings time (0 or 1): ",$isdst,"\n";
}#endsub

&epoch_conversion($EPOCH);



Reference Literature


1. Perl Cookbook

2. Perl Programming

3. PERL Black Book



www.cyberthinc.com