【问题标题】:How do I find the difference of two dates?如何找到两个日期的差异?
【发布时间】:2017-07-07 12:30:28
【问题描述】:
我有2017-01-12T17:23:14.000-0800格式的日期时间字符串
在 Perl 中,有没有简单的方法可以解析这样的两个日期并找出差异,而无需单独提取字符串中的所有字段?
例如,给定 2017-01-12T17:23:14.000-0800 和 2017-01-13T17:23:14.000-0800,我想要的差异是 1 天(此输出的任何合理格式都可以)。
【问题讨论】:
标签:
string
perl
parsing
datetime
【解决方案1】:
use DateTime::Format::Strptime qw( );
my $format = DateTime::Format::Strptime->new(
pattern => '%Y-%m-%dT%H:%M:%S.%3N%Z',
on_error => 'croak',
);
my $dt1 = $format->parse_datetime('2017-01-12T17:23:14.000-0800');
my $dt2 = $format->parse_datetime('2017-01-13T17:23:14.000-0800');
my ($y, $m, $d, $H, $M, $S) =
( $dt2 - $dt1 )->in_units(qw( years months days hours minutes seconds ));
替代品
my ($y, $m, $d) = $dt2->delta_md($dt1)->in_units(qw( years months days ));
my ($m, $d) = $dt2->delta_md($dt1)->in_units(qw( months days ));
my $d = $dt2->delta_days($dt1)->in_units(qw( days ));
my $S = $dt2->delta_ms($dt1)->in_units(qw( seconds ));
【解决方案2】:
Time::Moment 支持指定的字符串表示。由于它不是格式良好的 ISO 8601 表示,我们需要将 lenient 选项传递给 from_string 构造函数。
my $tm1 = Time::Moment->from_string('2017-01-12T17:23:14.000-0800', lenient => 1);
my $tm2 = Time::Moment->from_string('2017-01-13T17:23:14.000-0800', lenient => 1);
say $tm1->delta_days($tm2);
输出:
1
为了全面披露,我是 Time::Moment 的作者。