in reply to More accurate way to calculate Date difference

Here is one way:

use strict; use warnings; use DateTime; my $dt1 = DateTime->new ( year => 2013, month => 9, day => 29, ); my $dt2 = DateTime->new ( year => 2013, month => 3, day => 29, ); my $dt3 = DateTime->new ( year => 2013, month => 3, day => 30, ); my $dur1 = $dt2->subtract_datetime($dt1); printf "29/03/2013 to 29/09/2013: %s months\n", $dur1->months; my $dur2 = $dt3->subtract_datetime($dt1); printf "30/03/2013 to 29/09/2013: %s months\n", $dur2->months;

Output:

17:44 >perl 1919_SoPW.pl 29/03/2013 to 29/09/2013: 6 months 30/03/2013 to 29/09/2013: 5 months 17:44 >

Update: Please see the correction by haukex, below.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: More accurate way to calculate Date difference
by haukex (Archbishop) on Aug 11, 2018 at 08:18 UTC

    Unfortunately, one has to be careful with DateTime::Duration objects' accessors: ->month only returns the "months" component of the difference. You usually want ->in_units instead, but note the limitations of conversion - for example, you can't convert a number of months to a number of days without knowing which months we're talking about (and that information is no longer available if we only have a duration), so you have to get both the months and days, and in_units will do the conversion from years to months for you.

    use warnings; use strict; use DateTime; my $dt1 = DateTime->new(year => 2013, month => 10, day => 1); my $dt2 = DateTime->new(year => 2018, month => 3, day => 31); my $dur1 = $dt2->subtract_datetime($dt1); print $dt1->ymd, " to ", $dt2->ymd, ": ", $dur1->months, " months - oops!\n"; my ($days,$months) = $dur1->in_units('days','months'); print $dt1->ymd, " to ", $dt2->ymd, ": ", "$months months, $days days", "\n"; __END__ 2013-10-01 to 2018-03-31: 5 months - oops! 2013-10-01 to 2018-03-31: 53 months, 30 days
Re^2: More accurate way to calculate Date difference
by Anonymous Monk on Aug 11, 2018 at 08:00 UTC
    That is great!
    Thank you so much!