使用 Perl,我如何以 YYYY-MM-DD 的形式比较日期? [英] Using Perl, how do I compare dates in the form of YYYY-MM-DD?

查看:46
本文介绍了使用 Perl,我如何以 YYYY-MM-DD 的形式比较日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 n 字符串的数组,格式为 YYYY-MM-DD(例如,2010-10-31").

I have an array with n strings in format of YYYY-MM-DD (Example, "2010-10-31").

如何将日期与此数组中的字符串进行比较?

How do I compare a date to the strings in this array?

比如删除30多天前的字符串?

For example, delete the strings more than 30 day ago?

推荐答案

use strict; use warnings;
use DateTime ();
use DateTime::Duration ();
use DateTime::Format::Natural ();

my $parser = DateTime::Format::Natural->new;
my $now    = DateTime->now;
my $delta  = DateTime::Duration->new( days => 30 );
my $cutoff = $now->subtract_duration( $delta );

my @new_dates = map  { $_->[1] }
                grep { -1 == $_->[0] }
                map  { 
                    chomp;
                    [
                        DateTime->compare(
                            $parser->parse_datetime( $_ ),
                            $cutoff
                        ),
                        $_ 
                    ]
                } <DATA>;

print "@new_dates";

__DATA__
2010-07-31
2010-08-31
2010-09-30
2010-10-31

这篇关于使用 Perl,我如何以 YYYY-MM-DD 的形式比较日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆