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

时间:2011-08-12 01:35:10

标签: 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; 

3 个答案:

答案 0 :(得分:5)

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

use DateTime;
my $date = DateTime->now;
$date->subtract(days => 3);
print $date->ymd;

事实上,您可以将其减少为:

print DateTime->now->subtract(days => 3)->ymd

答案 1 :(得分:4)

改为使用printf

printf "%d-%02d-%02d", $year, $month, $day;

提供如下输出:

C:\perl>perl -we "printf qq(%d-%02d-%02d), 2011,5,4"
2011-05-04
C:\perl>perl -we "printf qq(%d-%02d-%02d), 2011,5,12"
2011-05-12
C:\perl>perl -we "printf qq(%d-%02d-%02d), 2011,22,12"
2011-22-12

答案 2 :(得分:2)

if($ month< 10)
{
$月= “0 $月”;
}

if($ day< 10)
{
$天= “0 $日”;
}