Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to format date

Tags:

datetime

perl

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;
like image 237
conandor Avatar asked Jul 09 '26 00:07

conandor


2 Answers

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
like image 64
cjm Avatar answered Jul 11 '26 13:07

cjm


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());
like image 41
Xaerxess Avatar answered Jul 11 '26 14:07

Xaerxess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!