Why does this perl DateTime math give unexpected results?

#!/usr/bin/perl use DateTime; $a = DateTime->new(year=>1952,month=>10,day=>21); $b = DateTime->new(year=>2015,month=>10,day=>31); $dif = $b-$a; print $dif->years() ." ". $dif->months() ." ". $dif->days(); # result: 63 0 3 

Where did he get 3 days from? My expectation is 63 0 10.

 #!/usr/bin/perl use DateTime; $a = DateTime->new(year=>1952,month=>11,day=>1); $b = DateTime->new(year=>2015,month=>10,day=>31); $dif = $b-$a; print $dif->years() ." ". $dif->months() ." ". $dif->days(); # result 62 11 2 

My expectation for this is 62 11 31 or so.

I am trying to make a base date of birth before math. The month and year seem to work as I expect, but this day seems unpredictable. I read the CPAN documentation, but I still do not understand.

+7
datetime time perl
source share
1 answer

$dif->years , $diff->months and in particular $diff->days do what you expect. From the documentation of DateTime :: Duration ...

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

Here, each method returns:

 $dur->years() == abs( $dur->in_units('years') ) $dur->months() == abs( ( $dur->in_units( 'months', 'years' ) )[0] ) $dur->weeks() == abs( $dur->in_units( 'weeks' ) ) $dur->days() == abs( ( $dur->in_units( 'days', 'weeks' ) )[0] ) 

If you think this is confusing, so will I.

You want in_units .

 # 63 0 10 say join " ", $dif->in_units('years', 'months', 'days'); 
+11
source share

All Articles