DateTime-Format-Natural

 view release on metacpan or  search on metacpan

lib/DateTime/Format/Natural.pm  view on Meta::CPAN

use strict;
use warnings;
use base qw(
    DateTime::Format::Natural::Calc
    DateTime::Format::Natural::Calendar
    DateTime::Format::Natural::Duration
    DateTime::Format::Natural::Expand
    DateTime::Format::Natural::Extract
    DateTime::Format::Natural::Formatted
    DateTime::Format::Natural::Helpers
    DateTime::Format::Natural::Rewrite
);
use boolean qw(true false);

use Carp qw(croak);
use DateTime ();
use DateTime::HiRes ();
use DateTime::TimeZone ();
use List::Util 1.33 qw(all any none);
use Params::Validate ':all';
use Scalar::Util qw(blessed);
use Storable qw(dclone);

use DateTime::Format::Natural::Utils qw(trim);

our $VERSION = '1.27';

validation_options(
    on_fail => sub
{
    my ($error) = @_;
    chomp $error;
    croak $error;
},
    stack_skip => 2,
);

sub new
{
    my $class = shift;

    my $self = bless {}, ref($class) || $class;

    $self->_init_check(@_);
    $self->_init(@_);

    return $self;
}

sub _init
{
    my $self = shift;
    my %opts = @_;

    my %presets = (
        lang           => 'en',
        format         => 'd/m/y',
        demand_future  =>  false,
        prefer_future  =>  false,
        time_zone      => 'floating',
        calendar_class =>  undef,
    );
    foreach my $opt (keys %presets) {
        $self->{ucfirst $opt} = $presets{$opt};
    }
    foreach my $opt (keys %opts) {
        if (defined $opts{$opt}) {
            $self->{ucfirst $opt} = $opts{$opt};
        }
    }
    $self->{Daytime} = $opts{daytime} || {};

    my $mod = join '::', (__PACKAGE__, 'Lang', uc $self->{Lang});
    eval "require $mod; 1" or die $@;

    $self->{data} = $mod->__new();
    $self->{grammar_class} = $mod;

    $self->{mode} = '';
}

sub _init_check
{
    my $self = shift;

    validate(@_, {
        calendar_class => {
            type => SCALAR | UNDEF,
            optional => true,
            callbacks => {
                'calendar class exists' => sub
                {
                    my $class = shift;
                    return true unless defined $class;
                    return $class eq 'DateTime::Calendar::Julian' && eval "require $class; 1";
                },
            },
        },
        demand_future => {
            # SCALARREF due to boolean.pm's implementation
            type => BOOLEAN | SCALARREF,
            optional => true,
            callbacks => {
                'mutually exclusive' => sub
                {
                    return true unless exists $_[1]->{prefer_future};
                    die "prefer_future provided\n";
                },
            },
        },
        lang => {
            type => SCALAR,
            optional => true,
            regex => qr!^(?:en)$!i,
        },
        format => {
            type => SCALAR,
            optional => true,
            regex => qr!^(?:
                           (?: (?: [dmy]{1,4}[-./] ){2}[dmy]{1,4} )
                             |
                           (?: [dm]{1,2}/[dm]{1,2} )
                         )$!ix,
        },
        prefer_future => {
            # SCALARREF due to boolean.pm's implementation
            type => BOOLEAN | SCALARREF,
            optional => true,
            callbacks => {
                'mutually exclusive' => sub
                {
                    return true unless exists $_[1]->{demand_future};
                    die "demand_future provided\n";
                },
            },
        },
        time_zone => {
            type => SCALAR | OBJECT,
            optional => true,
            callbacks => {
                'valid timezone' => sub
                {
                    my $val = shift;
                    if (blessed($val)) {
                        return $val->isa('DateTime::TimeZone');
                    }
                    else {
                        eval { DateTime::TimeZone->new(name => $val) };
                        return !$@;
                    }
                }

lib/DateTime/Format/Natural.pm  view on Meta::CPAN

DateTime::Format::Natural - Parse informal natural language date/time strings

=head1 SYNOPSIS

 use DateTime::Format::Natural;

 $parser = DateTime::Format::Natural->new;

 $dt = $parser->parse_datetime($date_string);
 @dt = $parser->parse_datetime_duration($date_string);

 $date_string  = $parser->extract_datetime($extract_string);
 @date_strings = $parser->extract_datetime($extract_string);

 if ($parser->success) {
     # operate on $dt/@dt, for example:
     print $dt->strftime('%d.%m.%Y %H:%M:%S'), "\n";
 } else {
     warn $parser->error;
 }

 @traces = $parser->trace;

 # examples

 12:14 PM
 next tuesday at 2am
 tomorrow morning
 4pm yesterday
 10 weeks ago

 1st tuesday last november
 2nd friday in august
 final thursday in april

 for 3 hours
 monday to friday
 1 April 10 am to 1 May 8am

 jan 24, 2011 12:00

=head1 DESCRIPTION

C<DateTime::Format::Natural> parses informal natural language date/time strings.
In addition, parsable date/time substrings may be extracted from ordinary strings.

=head1 CONSTRUCTOR

=head2 new

Creates a new C<DateTime::Format::Natural> object. Arguments to C<new()> are options and
not necessarily required.

 $parser = DateTime::Format::Natural->new(
           datetime       => DateTime->new(...),
           lang           => 'en',
           format         => 'mm/dd/yy',
           prefer_future  => [0|1],
           demand_future  => [0|1],
           time_zone      => 'floating',
           calendar_class => 'DateTime::Calendar::Julian',
           daytime        => { morning   => 06,
                               afternoon => 13,
                               evening   => 20,
                             },
 );

=over 4

=item * C<datetime>

Overrides the present now with a L<DateTime> object provided.

=item * C<lang>

Contains the language selected, currently limited to C<en> (english).
Defaults to 'C<en>'.

=item * C<format>

Specifies the format of numeric dates.

The format is used to influence how numeric dates are parsed. Given two
numbers separated by a slash, the month/day order expected comes from
this option. If there is a third number, this option describes where
to expect the year. When this format can't be used to interpret the
date, some unambiguous dates may be parsed, but there is no form
guarantee.

Current supported "month/day" formats: C<dd/mm>, C<mm/dd>.

Current supported "year/month/day" formats (with slashes): C<dd/mm/yy>,
C<dd/mm/yyyy>, C<mm/dd/yyyy>, C<yyyy/mm/dd>.

Note that all of the above formats with three units do also parse
with dots or dashes as format separators.

Furthermore, formats can be abbreviated as long as they remain
unambiguous.

Defaults to 'C<d/m/y>'.

=item * C<prefer_future>

Prefers future time and dates. Accepts a boolean, defaults to false.

=item * C<demand_future>

Demands future time and dates. Similar to C<prefer_future>, but stronger.
Accepts a boolean, defaults to false.

=item * C<time_zone>

The time zone to use when parsing and for output. Accepts any time zone
recognized by L<DateTime>. Defaults to 'floating'.

=item * C<calendar_class>

The calendar class used for fixed-date holidays such as C<christmas day>.
Accepts C<DateTime::Calendar::Julian>. Defaults to 'C<gregorian>'.

=item * C<daytime>

A hash reference consisting of customized daytime hours,
which may be selectively changed.

=back

=head1 METHODS

=head2 parse_datetime

Returns a L<DateTime> object constructed from a natural language date/time string.

 $dt = $parser->parse_datetime($date_string);
 $dt = $parser->parse_datetime(string => $date_string);

=over 4

=item * C<string>

The date string.

=back

=head2 parse_datetime_duration

Returns one or two L<DateTime> objects constructed from a natural language
date/time string which may contain timespans/durations. I<Same> interface
and options as C<parse_datetime()>, but should be explicitly called in
list context.

 @dt = $parser->parse_datetime_duration($date_string);
 @dt = $parser->parse_datetime_duration(string => $date_string);

=head2 extract_datetime

Returns parsable date/time substrings (also known as expressions) extracted
from the string provided; in scalar context only the first parsable substring
is returned, whereas in list context all parsable substrings are returned.
Each extracted substring can then be passed to the C<parse_datetime()>/
C<parse_datetime_duration()> methods.

 $date_string  = $parser->extract_datetime($extract_string);
 @date_strings = $parser->extract_datetime($extract_string);
 # or
 $date_string  = $parser->extract_datetime(string => $extract_string);
 @date_strings = $parser->extract_datetime(string => $extract_string);

=head2 success

Returns a boolean indicating success or failure for parsing the date/time
string given.

=head2 error

Returns the error message if the parsing did not succeed.

=head2 trace



( run in 0.663 second using v1.01-cache-2.11-cpan-f52f0507bed )