Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
My code below:
use strict; use warnings; use Date::Calc qw(:all); my $date_birth = '1999-12-13'; my $date_death = '2080-05-21'; my @array_birth = split(/-/, $date_birth); my @array_death = split(/-/, $date_death); my $dd = Delta_Days(@array_birth, @array_death); my $years_alive = sprintf("%.1f", $dd/365); print $years_alive,"\n";
works ok I would say, but I guess it is not 100% accurate (since I assume years of 365 days and I do not take into account months and days of birth and death.
Can you help me fix it?

Replies are listed 'Best First'.
Re: Date::Calc in years?
by choroba (Cardinal) on Oct 18, 2018 at 09:22 UTC
    That's what Delta_YMD, or even N_Delta_YMD are for:
    my ($dy, $dm, $dd) = N_Delta_YMD(@array_birth, @array_death); print "$dy years, $dm months, $dd days\n";

    Without N_, the result would be

    81 years, -7 months, 8 days

    N_ fixes the negative number:

    80 years, 5 months, 8 days

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      Thank you very much!
Re: Date::Calc in years?
by BillKSmith (Monsignor) on Oct 18, 2018 at 19:18 UTC
    There is no way to avoid thinking about special cases. Documentation for the module says that it does what is "intuitive". That may not meet your requirements in all cases. You still have to identify special cases, specify the result you expect, and verify that any proposed solution handles them correctly. Remember, if this issue were not important, you probably would not have asked the question in the first place.
    Bill
Re: Date::Calc in years?
by thanos1983 (Parson) on Oct 19, 2018 at 22:41 UTC

    Hello Anonymous Monk,

    Fellow Monks have provided a solution to your problem, but just to add an alternative:

    You can use the module Date::Manip, which handles really good the dates.

    #!/usr/bin/perl use strict; use warnings; use Date::Manip; use feature 'say'; my $date1 = ParseDate("1999-12-13"); my $date2 = ParseDate("2080-05-21"); say Delta_Format(DateCalc($date1, $date2, "approx"), 1, "Years:\t%yv\nMonths:\t%Mv\nWeeks:\t%wv\nDays:\t%dv"); __END__ $ perl test.pl Years: 80 Months: 5 Weeks: 1 Days: 1

    Update: New print out format.

    Hope this helps, Best Regards.

    Seeking for Perl wisdom...on the process of learning...not there...yet!
Re: Date::Calc in years?
by Anonymous Monk on Oct 18, 2018 at 09:18 UTC
    Fix what?
      I mean to not just divide the total number of days/365 in order to find the years, since it is not always the case.