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
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
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.
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
Hope this write-up was helpful. Happy coding.
Basics
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.
tarunt
like this

