How can I parse relative dates with Perl?

前端 未结 4 1540
失恋的感觉
失恋的感觉 2021-01-02 05:34

I\'d love to know if there is a module to parse \"human formatted\" dates in Perl. I mean things like \"tomorrow\", \"Tuesday\", \"next week\", \"1 hour ago\".

My re

4条回答
  •  没有蜡笔的小新
    2021-01-02 05:55

    Date::Manip does exactly this.

    Here is an example program:

    #!/usr/bin/perl
    
    use strict;
    use Date::Manip;
    
    while ()
    {
      chomp;
      print UnixDate($_, "%Y-%m-%d %H:%M:%S"),  " ($_)\n";
    }
    
    __DATA__
    today
    yesterday
    tomorrow
    last Tuesday
    next Tuesday
    1 hour ago
    next week
    

    Which results in the following output:

    2008-11-17 15:21:04 (today)
    2008-11-16 15:21:04 (yesterday)
    2008-11-18 15:21:04 (tomorrow)
    2008-11-11 00:00:00 (last Tuesday)
    2008-11-18 00:00:00 (next Tuesday)
    2008-11-17 14:21:04 (1 hour ago)
    2008-11-24 00:00:00 (next week)
    

    UnixDate is one of the functions provided by Date::Manip, the first argument is a date/time in any format that the module supports, the second argument describes how to format the date/time. There are other functions that just parse these "human" dates, without formatting them, to be used in delta calculations, etc.

提交回复
热议问题