Perl Epoch Converter Routines

How to convert epoch / UNIX timestamps to normal readable date/time using Perl.

Getting current epoch time in Perl

Time returns an integer with the current epoch:

time

Converting from epoch to normal date in Perl

Using the internal localtime or gmtime functions, localtime and gmtime return an array:

my $time = time;	# or any other epoch timestamp
my @months = ("Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec");
my ($sec, $min, $hour, $day,$month,$year) = (localtime($time))[0,1,2,3,4,5];
# You can use 'gmtime' for GMT/UTC dates instead of 'localtime'
print "Unix time ".$time." converts to ".$months[$month]." ".$day.", ".($year+1900);
print " ".$hour.":".$min.":".$sec."\n";

But you can also use the scalar function to display your date with far less code:
print scalar localtime(946684800); returns Sat Jan 1 01:00:00 2000 (in my timezone).

For more advanced date manipulation, try using the DateTime module:

use DateTime;
$dt = DateTime->from_epoch( epoch => $epoch );

$year   = $dt->year;
$month  = $dt->month; # 1-12 - you can also use '$dt->mon'
$day    = $dt->day; # 1-31 - also 'day_of_month', 'mday'
$dow    = $dt->day_of_week; # 1-7 (Monday is 1) - also 'dow', 'wday'
$hour   = $dt->hour; # 0-23
$minute = $dt->minute; # 0-59 - also 'min'
$second = $dt->second; # 0-61 (leap seconds!) - also 'sec'
$doy    = $dt->day_of_year; # 1-366 (leap years) - also 'doy'
$doq    = $dt->day_of_quarter; # 1.. - also 'doq'
$qtr    = $dt->quarter; # 1-4
$ymd    = $dt->ymd; # 1974-11-30
$ymd    = $dt->ymd('/'); # 1974/11/30 - also 'date'
$hms    = $dt->hms; # 13:30:00
$hms    = $dt->hms('|'); # 13|30|00 - also 'time'

Converting from normal date to epoch in Perl

Using the Time::Local module:

use Time::Local;
my $time = timelocal($sec,$min,$hours,$day,$month,$year);
# replace 'timelocal' with 'timegm' if your input date is GMT/UTC

Using the DateTime module:

use DateTime;
$dt = DateTime->new( year => 1974, month => 11, day => 30, hour => 13, minute => 30,
	second => 0, nanosecond => 500000000, time_zone => 'Asia/Taipei' );
$epoch_time  = $dt->epoch;

Find more detailed information on CPAN: Time::Local, DateTime. You can also use Date::Manip if you need more advanced date manipulation routines.

Using the Date::Parse module (thanks to ericblue76):

use Date::Parse;
print str2time("02/25/2011 11:50AM");

The Perl Cookbook, Second Edition gives detailed information on manipulating dates and times in chapter 3 (pages 90-110).


Comments and questions


« Epoch Converter Functions