Date :: Calc - 格式化日期和月份

cap*_*ser 5 perl date

我想在这里做的就是如果日期或月份是一个数字,在它前面添加一个零.现在它打印出日期为201188,我正在寻找20110808.

#!/usr/bin/perl
use Date::Calc qw(Add_Delta_Days); 
my (undef, undef, undef, $day, $month, $year) = localtime(); 
$year +=1900; 
$month +=1; 
($year, $month, $day ) = Add_Delta_Days($year, $month, $day, -3)
if ($month =~ /\d{1}/){
    s/$month/0$month/
}  
if ($day =~/\d{1}/){ 
    s/$day/0$day/
}
print $year,$month,$day; 
Run Code Online (Sandbox Code Playgroud)

RET*_*RET 5

如果您乐意使用Date::Calc,为什么不使用DateTime

use DateTime;
my $date = DateTime->now;
$date->subtract(days => 3);
print $date->ymd;
Run Code Online (Sandbox Code Playgroud)

事实上你可以减少到:

print DateTime->now->subtract(days => 3)->ymd
Run Code Online (Sandbox Code Playgroud)


And*_*rey 2

if ($month < 10)
{
     $month="0$month"; }
}

if ($day < 10)
{
     $day="0$day";
}

  • 请不要。如果将结果交给其他地方,Perl 将再次跳过前导零,因为它将把字符串作为数字处理。使用 printf 进行格式化打印。 (2认同)