Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/articles/perl-tutorials/)
-   -   Format Date/Time in Perl (http://www.go4expert.com/articles/format-date-time-perl-t15533/)

pradeep 17Dec2008 23:51

Format Date/Time 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 http://perldoc.perl.org/functions/localtime.html

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 http://www.mkssoftware.com/docs/man3/strftime.3.asp

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 http://search.cpan.org/~stbey/Date-Calc-5.4/Calc.pod

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.

debleena_doll2002 19Dec2008 10:35

Re: Format Date/Time in Perl
Nice article....I have taken printout of it ...n will read @ home..

NDL 21Dec2008 12:53

Re: Format Date/Time in Perl
Nice :D

shabbir 6Jan2009 12:24

Re: Format Date/Time in Perl
Nomination for article of the month for December 2008 Started.

ruby20 10Jan2009 15:40

Re: Format Date/Time in Perl
Nice article.....

unni krishnan.r 31May2010 17:06

Re: Format Date/Time in Perl

AllyUnion 20Jun2011 22:34

Re: Format Date/Time in Perl
There is a bug in the code...

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

All times are GMT +5.5. The time now is 17:42.