Format Date/Time in Perl

pradeep's Avatar author of Format Date/Time in Perl
This is an article on Format Date/Time in Perl in Perl.
Working with dates is a very common feature of any application, be it a web app or a desktop one. Some people consider Perl to be a language where working with dates is hard, but basically it's quite easy if you know how to. Datetime is a common term while refering to date and time together.


Basic formatting of datetime in Perl is done by writing your own formatting logic, we'll use the localtime function to get the current datetime details. For more info about the locatime function checkout

Code: Perl
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900; ## $year contains no. of years since 1900, to add 1900 to make Y2K compliant
my @month_abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );

print "$abbr[$mon] $mday"; ## gives Dec 17

Enter POSIX::strftime

The strftime function helps to format time information to string using pre-defined formatting parameters. Here's how we go about it, you might need a list of formatting string codes found at

Code: Perl
use POSIX qw/strftime/;

print strftime('%D %T',localtime); ## outputs 12/17/08 10:08:35
print strftime('%d-%b-%Y %H:%M',localtime); ## outputs 17-Dec-2008 10:08

You can format the way you like it using the format parameters, I personally feel this is the easiest way to format datetime in Perl for daily use.

Using Date::Calc

The Perl module Date::Calc's primary use is date manipulation, but it may also be used formatting dates to some extent, you may read the module's docs at

Code: Perl
use Date::Calc qw/Date_to_Text Date_to_Text_Long Today/;

my @date_today = Today();

print Date_to_Text(@date_today);
print Date_to_Text_Long(@date_today);

Hope this write-up was helpful. Happy coding.
tarunt like this
debleena_doll2002's Avatar
Ambitious contributor
Nice article....I have taken printout of it ...n will read @ home..
NDL's Avatar, Join Date: Oct 2008
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Nomination for article of the month for December 2008 Started.
ruby20's Avatar
Light Poster
Nice article.....
unni krishnan.r's Avatar, Join Date: Apr 2010
Skilled contributor
AllyUnion's Avatar, Join Date: Jun 2011
Newbie Member
There is a bug in the code...

"$abbr[$mon] $mday";
Should be:
"$month_abbr[$mon] $mday";