13

我正在编写一个 perl 脚本来为日期添加天数并显示新日期:

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 例如:my $date = "20030102"

输出也需要是:20030303

谢谢

4

3 回答 3

14

您使用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');
于 2012-10-29T19:13:08.823 回答
13

您可以使用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
于 2012-10-29T14:45:01.737 回答
5

将 $date 从输入格式转换为旧格式:

$date =~ s%(....)(..)(..)%$3/$2/$1%;

如果输出格式不应该是%m/%d/%Y,则不要将其设置为它。你显然需要%Y%m%d.

于 2012-10-29T13:30:37.563 回答