robert laing
robert laing

Reputation: 1401

How to find the difference between two dates in perl?

In perl, given a user inputted date, how can I check that is not greater 12 months from today?

I tried this way:

#!/usr/bin/env perl
use 5.010;
use warnings;
use DateTime;
use Data::Dumper;

$given = DateTime->new( year=>"2013", month => "11", day =>"23" );
$now = DateTime->now;
$delta = $given->delta_md($now);

say $delta->months;
print Dumper($delta);

But the output I got was this. Why $delta->months value is different than that showed from dumper?

11
$VAR1 = bless( {
                 'seconds' => 0,
                 'minutes' => 0,
                 'end_of_month' => 'wrap',
                 'nanoseconds' => 0,
                 'days' => 24,
                 'months' => 23
               }, 'DateTime::Duration' );

Upvotes: 3

Views: 4224

Answers (3)

ikegami
ikegami

Reputation: 385655

my $limit = DateTime->new( year=>"2013", month => "11", day =>"23" );
my $today = DateTime->today();

if ($now->clone()->add( months => 12 ) > $limit) {
   ...
}

Upvotes: 0

Nikodemus RIP
Nikodemus RIP

Reputation: 1379

The method months in DateTime::Duration is the remainder month part of the duration after conversion to the larger unit (year). The internal data structure stores the complete duration (1a, 11m) in a different way.

years, months, weeks, days, hours, minutes, seconds, nanoseconds

These methods return numbers indicating how many of the given unit the object represents, after having done a conversion to any larger units. For example, days are first converted to weeks, and then the remainder is returned. These numbers are always positive.

To get this value I think you need $dur->in_units( 'months' );.

Upvotes: 6

choroba
choroba

Reputation: 241828

$delta->months is always < 12. Check that $delta->years > 1.

Upvotes: 2

Related Questions