I wrote a perl script to get datetime. It do work but I do wonder if there any easier way to format date as output.
#!/usr/bin/perl
use DateTime;
my $dt
DateTime provides the format_cldr
method for this:
use DateTime;
my $myTimeStamp = DateTime->now->subtract( days => 1 );
printf "--> %s\n", $myTimeStamp->format_cldr('yyyy MM dd HH');
# --> 2012 02 28 02
Sure, use POSIX module:
The POSIX module permits you to access all (or nearly all) the standard POSIX 1003.1 identifiers.
Example:
use POSIX;
print POSIX::strftime('%d-%m-%Y %H:%M:%S', localtime());
For re-formatting dates, as noted, there is the POSIX core module. You would be remiss not to look at the core module Time::Piece too, which not only delivers strftime()
but also strptime()
to provide very flexible date/time parsing. Time::Piece
appeared in Perl core in 5.9.5.
use strict;
and use warnings;
at the start of your program and declare all your variables close to their first use. This applies especially if you are seeking help as it will find a lot of simple errors that aren't immediately obvious.It is best to use printf
if you want to zero-pad any output. There is also no need to extract the date fields to separate variables. Is the output you have shown the one you ultimately want? This program does the same thing as the code you have posted.
use strict;
use warnings;
use DateTime;
my $myTimeStamp = DateTime->now->subtract( days => 1 );
printf "--> %04d %02d %02d %02d\n", map $myTimeStamp->$_, qw/year month day hour/;
OUTPUT
--> 2012 02 28 12