【问题标题】:How can I create relative/approximate dates in Perl?如何在 Perl 中创建相对/近似日期?
【发布时间】:2010-11-09 10:03:16
【问题描述】:

我想知道是否有任何库(最好是DateTime-esque)可以采用正常的日期时间并创建适当的相对人类可读日期。 本质上与更常见的问题完全相反:How can I parse relative dates with Perl?

显然,确切的措辞/解释取决于实际实施,但我希望提供一种一致的方式来指定未来的日期。知道像“due in 2 weeks”这样的近似值(对我来说)比“due on 2009-07-30”更有助于掌握我还剩下多少时间。

例子:

2009-07-06        => "in 1 year"
2009-07-30        => "in 2 weeks"
2009-07-09        => "tomorrow"
2009-07-09 12:32  => "tomorrow at 12:32"
2009-07-12 05:43  => "monday morning"
2009-07-03 05:74  => "6 days ago"

【问题讨论】:

    标签: perl datetime nlp relative-date


    【解决方案1】:

    更新:看起来这个功能是在Template Toolkit Plugin 中实现的。我将把我的其余答案留在这里以供参考,但Template::Plugin::DtFormatter 可能是最好的查看位置。

    查看该模块的源代码,我被引导到DateTime::Format::Natural,这似乎与您想要的有关。

    上一个答案:

    查看Date::Calc 以使用Delta_DHMS 为您提供增量。您应该能够使用这些增量来选择日期的措辞方式。

    这是一个非常基本的起点。它是错误的,但说明了基本思想。添加逻辑来品味。

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Date::Calc qw(:all);
    use Lingua::EN::Inflect qw( NO );
    
    my @dates = (
        [ 2009, 7,  6 ],
        [ 2009, 7, 30 ],
        [ 2009, 7,  9 ],
        [ 2009, 7,  9, 12, 32 ],
        [ 2009, 7, 12,  5, 43 ],
        [ 2009, 7,  3,  5, 14 ],
        [ 2010, 8, 9 ],
        [ 2012, 8, 9 ],
        [ 2013, 8, 9 ],
    );
    
    for my $date ( @dates ) {
        print "@$date: ", relative_when( $date ), "\n";
    }
    
    sub relative_when {
        my ($year, $month, $day, $hour, $min, $sec) = @{ $_[0] };
        my ($Dyear, $Dmon, $Dday, $Dhr, $Dmin, $Dsec) = Delta_YMDHMS(
            Today_and_Now(),
            $year, $month, $day, $hour || 0, $min || 0, $sec || 0
        );
        return NO('year',  $Dyear )     if $Dyear > 0;
        return NO('month', $Dmon )      if $Dmon  > 0;
        return NO('week',  int($Dday/7) if $Dday  > 6;
        return NO('day',   $Dday)       if $Dday  > 1;
        return 'tomorrow' if $Dday == 1;
        return 'today'    if $Dday == 0;
        return "";
    }
    
    __END__
    

    输出:

    C:\Temp> dfg
    2009 7 6:
    2009 7 30: 2 weeks
    2009 7 9: today
    2009 7 9 12 32: today
    2009 7 12 5 43: 2 days
    2009 7 3 5 14:
    2010 8 9: 1 year
    2012 8 9: 3 years
    2013 8 9: 4 years
    

    【讨论】:

    • 我知道,对吧?人们会对这个网站上的任何内容投反对票。没必要刻薄!
    【解决方案2】:

    查看 Twitter Fan Wiki 上的 Relative Time Scripts

    【讨论】:

      【解决方案3】:

      Date::Manip 对于这样的事情非常强大,但比Date::Calc 慢。

      【讨论】:

        猜你喜欢
        • 2010-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        相关资源
        最近更新 更多