in reply to Re: More accurate way to calculate Date difference
in thread More accurate way to calculate Date difference
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
|
|---|