Question

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->now( time_zone => 'local' );
$myTimeStamp    = $dt->subtract( days => 1 );
$myYear         = $myTimeStamp->year;
$myMonth        = $myTimeStamp->month;
if ( length( $myMonth ) == 1 ) {
    $myMonth = "0$myMonth";
}
$myDay          = $myTimeStamp->day;
if ( length( $myDay ) == 1 ) {
    $myDay = "0$myDay";
}
$myHour         = $myTimeStamp->hour;
if ( length( $myHour ) == 1 ) {
    $myHour = "0$myHour";
}
#$myDir          = "/var/tmp/logs/$myYear/$myMonth/$myYear$myMonth-";

print "--> $myYear $myMonth $myDay $myHour\n";
# --> 2012 02 28 02
exit 0;
Was it helpful?

Solution

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

OTHER TIPS

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());
  • First of all always 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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top