我想在格式%Y%m%d中每次通过循环减去一天,但是当我运行此代码时,它会显示一些奇怪的数字。
my $date = Time::Piece->strptime("20170306", "%Y%m%d");
$date = $date->strftime("%Y%m%d");
my $i = 7;
while($i > 0) {
$date -= ONE_DAY;
print "Date: " . $date . "\n";
$i--;
}
输出:
Date: 20083906
Date: 19997506
Date: 19911106
Date: 19824706
Date: 19738306
Date: 19651906
Date: 19565506
答案 0 :(得分:4)
每次迭代都需要使用strftime
。不要分配该调用的返回值$date
,否则它将用字符串覆盖您的对象。这条线错了:
$date = $date->strftime("%Y%m%d");
我已从您的代码中删除了此示例的解析,因为我不知道您的输入是什么。
use strict;
use warnings;
use Time::Piece;
use Time::Seconds;
my $date = localtime;
my $i = 7;
while($i > 0) {
$date -= ONE_DAY;
printf "Date: %s\n", $date->strftime('%Y%m%d');
$i--;
}
这将打印一份从今天开始的日期列表。
Date: 20170312
Date: 20170311
Date: 20170310
Date: 20170309
Date: 20170308
Date: 20170307
Date: 20170306