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

标签 perl iso8601

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

最佳答案

DateTime::Format::Duration::ISO8601 ,它可以将 ISO 8601 持续时间字符串转换为 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%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

关于perl - 在 perl 中将 ISO8601 持续时间(P3Y6M ...)转换为秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46949468/

相关文章:

c++ - 使用 ICU 解析带有可选小数秒的 ISO 8601 日期时间

oracle - Unix 时间戳到 ISO-8601 字符串

datetime - 这是一个有效的 ISO 8601 格式的字符串吗?

regex - 去除字符串但允许变音

带有附加配置文件的 perlcritic

parsing - Golang 解析时间.Duration

java - Java 中的 RFC822 时区解析

regex - 如何使用 s///运算符将字符插入到字符串中?

regex - Perl 匹配只返回 "1"。 bool 人?为什么?

regex - 如何在 Perl 标量中只保留前五行?