Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse relative dates with Perl?

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 research with CPAN suggest that there is no such module, so how would you go about creating one? NLP is way over the top for this.

like image 876
andymurd Avatar asked Nov 17 '08 20:11

andymurd


1 Answers

Date::Manip does exactly this.

Here is an example program:

#!/usr/bin/perl

use strict;
use Date::Manip;

while (<DATA>)
{
  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.

like image 187
Robert Gamble Avatar answered Oct 04 '22 11:10

Robert Gamble