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

use DateTime; use Data::Dumper; my $date = DateTime->now; my $dur = $date->subtract_datetime( DateTime->now->subtract( years => +1, months => 1 ) ); print "\nmonths: " . $dur->in_units( 'months' ) . "\ndays: " . $dur->i +n_units( 'days' ) . "\n"; __OUTPUT__ months: 13 days: 0 ^^^^^^^
I would expect it to count the days between the two dates. When examining $dur with Data::Dumper I discovered that it only remembers the difference in months - and since it does not know which months are involved it cannot count the days.

Replies are listed 'Best First'.
Re: How can I count the days between two dates?
by ikegami (Patriarch) on Nov 04, 2008 at 17:24 UTC
    use DateTime; my $today = DateTime->today( time_zone => 'local' ); my $dur = $today->delta_days( $today->clone->subtract( years => 1, months => 1 ) ); print( $dur->in_units( 'days' ), " days\n" );

    There's also ->delta_md if you want month+days instead of just days.

      Thanks! delta_days did the trick.
Re: How can I count the days between two dates?
by Your Mother (Archbishop) on Nov 04, 2008 at 17:47 UTC

    Here's a snippet I use a lot at home-

    use Date::Calc "Delta_Days"; my $first = shift || die "Give two date strings YYYYMMDD YYYYMMDD\n"; my $second = shift || die "Give two date strings YYYYMMDD YYYYMMDD\n"; my $days = Delta_Days( $first =~ /(\d\d\d\d)(\d\d)(\d\d)/, $second =~ /(\d\d\d\d)(\d\d)(\d\d)/ ); print $days, $/;

    Though I love the DateTime stuff when anything gets much hairier than that.

Re: How can I count the days between two dates?
by Fletch (Bishop) on Nov 04, 2008 at 17:46 UTC
      The problem is that the duration is expressed in months (as shown below). Converting month to days is not a formatting issue. I don't see how that module would help. Am I missing something?
      $VAR1 = bless( { 'seconds' => 0, 'minutes' => 0, 'end_of_month' => 'wrap', 'nanoseconds' => 0, 'days' => 0, 'months' => 13 }, 'DateTime::Duration' );

        If he's specifically interested in just the number of days, then yes you're correct it's not a solution (hence the "Possibly" :). However if the actual problem is showing a duration in a hyooman friendly representation that module is capable of normalizing a duration into the smallest possible units of each (and its logic in doing so using a base date may be of use figuring out how to approach the problem if the actual number of days is the real goal; the section on normalization in the docs mentions it under "Months of unequal length").

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.