将 ISO8601 持续时间(P3Y6M ...)转换为 perl 中的秒数

Converting ISO8601 duration (P3Y6M...) to seconds in perl

我正在尝试将 ISO 8601 持续时间格式 P3Y6M4DT12H30M5S 转换为 perl 中的秒数。有做这个的图书馆吗?我试过搜索,但只找到了一个 js 库。查看 DateTime 和 Time::Moment 也没有提供解决方案。

DateTime::Format::Duration::ISO8601, which can convert the ISO 8601 duration string into a DateTime::Duration 个对象。然后您可以将其转换为秒。

use DateTime::Duration;
use DateTime::Format::Duration::ISO8601;

my $format = DateTime::Format::Duration::ISO8601->new;
my $d = $format->parse_duration('P3Y6M4DT12H30M5S');

但是,DateTime::Duration 格式不能用于将年转换为秒,如 in the docs here 所述。

The last example demonstrates that there will not be any conversion between units which don't have a fixed conversion rate. The only conversions possible are:

years <=> months
weeks <=> days
hours <=> minutes
seconds <=> nanoseconds

For the explanation of why this is the case, please see the How DateTime Math Works section of the DateTime.pm documentation

您可以使用 DateTime::Format::Duration with the %s pattern 来规避它。完整的实现可能如下所示。

use DateTime::Duration;
use DateTime::Format::Duration::ISO8601;
use DateTime::Format::Duration;

my $format = DateTime::Format::Duration::ISO8601->new;
my $d      = $format->parse_duration('P3Y6M4DT12H30M5S');

my $output_format = DateTime::Format::Duration->new( pattern => '%s' );
print $output_format->format_duration($d);

或者,简而言之,如果您只需要一次。

use DateTime::Duration;
use DateTime::Format::Duration::ISO8601;
use DateTime::Format::Duration;

print DateTime::Format::Duration->new( pattern => '%s' )
    ->format_duration(
    DateTime::Format::Duration::ISO8601->new->parse_duration('P3Y6M4DT12H30M5S') );

这两个都会打印

109254605