Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the difference between two dates in perl?

Tags:

date

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' );
like image 400
robert laing Avatar asked Feb 02 '26 05:02

robert laing


2 Answers

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' );.

like image 169
Nikodemus RIP Avatar answered Feb 03 '26 17:02

Nikodemus RIP


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

like image 37
choroba Avatar answered Feb 03 '26 17:02

choroba