在 Perl 中将时间添加到 ISO 8601 时间

Add time to ISO 8601 times in Perl

我有一个 ISO 8601 时间存储在一个变量中,我有一些小时数存储在另一个变量中,如下所示:

my $current_time = shift; #looks like: 2015-07-01T15:38:08Z
my $hours = shift; # looks like: 12

我的目标是将小时添加到当前时间,但似乎没有任何内置的 Perl 函数可以执行此操作。在 Powershell 中,你可以这样做:

$currentTime = $currentTime .AddHours($hours)

有没有在 Perl 中执行此操作的简单方法?

使用 Time::Piece 相当简单:

#! /usr/bin/perl
use warnings;
use strict;

use Time::Piece;
use Time::Seconds;

my $current_time = '2015-07-01T15:38:08Z';
my $hours = 12;

my $format = '%Y-%m-%dT%H:%M:%SZ';
my $time = 'Time::Piece'->strptime($current_time, $format);
$time += $hours * ONE_HOUR;

print $time->strftime($format), "\n";

该特定的 ISO 8601 配置文件也称为 RFC3339。

use DateTime::Format::RFC3339;

my $dt = DateTime::Format::RFC3339->parse_datetime('2015-07-01T15:38:08Z');
$dt->add( hours => 1 );
print "$dt\n";  # 2015-07-01T16:38:08Z

如果您想接受任意 ISO 8601 配置文件,您可以使用 DateTime::Format::ISO8601。

use DateTime::Format::ISO8601;

my $dt = DateTime::Format::ISO8601->parse_datetime('2015-07-01T15:38:08Z');
$dt->set_time_zone('UTC');  # Convert to UTC ("Z") if it's not already.
$dt->add( hours => 1 );
print $dt->iso8601().'Z', "\n";  # 2015-07-01T16:38:08Z

我发布了这些替代方案,因为这些模块使用起来比 Time::Piece 更不容易出错。

您也可以使用Time::Moment。为了全面披露,我是 Time::Moment.

的作者
say Time::Moment->from_string('2015-07-01T15:38:08Z')
                ->plus_hours(1);

输出:

2015-07-01T16:38:08Z