我正在处理一个perl脚本,为日期添加天数并显示newdate:
use Time::ParseDate;
use Time::CTime;
my $date = "02/01/2003";
my $numdays = 30;
my $time = parsedate($date);
# add $numdays worth of seconds
my $newtime = $time + ($numdays * 24 * 60 * 60);
my $newdate = strftime("%m/%d/%Y",localtime($newtime));
print "$newdate\n";
The output will be:
03/03/2003
现在如何将日期字段的输入设置为yyyymmdd Ex:my $ date =“20030102”
输出也需要:20030303
谢谢
答案 0 :(得分:11)
您使用Time::Piece + Time::Seconds(自Perl 5.10以来的核心),
use Time::Piece ();
use Time::Seconds;
my $date = '20030102';
my $numdays = 60; # 30 doesn't get us to march
my $dt = Time::Piece->strptime( $date, '%Y%m%d');
$dt += ONE_DAY * $numdays;
print $dt->strftime('%Y%m%d');
答案 1 :(得分:9)
您可以使用DateTime
+ DateTime::Format::Strptime
:
#!/usr/bin/perl
use strict;
use DateTime;
use DateTime::Format::Strptime;
my $strp = DateTime::Format::Strptime->new(
pattern => '%m/%d/%Y'
);
# convert date to
my $date = '02/01/2003';
my $dt = $strp->parse_datetime($date);
printf "%s -> %s\n", $date, $dt->add(days => 30)->strftime("%d/%m/%Y");
<强>输出强>
02/01/2003 -> 03/03/2003
答案 2 :(得分:5)
将$ date从输入格式转换为旧格式:
$date =~ s%(....)(..)(..)%$3/$2/$1%;
如果输出格式不应为%m/%d/%Y
,则不要将其设置为%Y%m%d
。你显然需要{{1}}。