On Jan 25, 2005, at 8:57 AM, Hill, Ronald wrote:
Hi Todd,
Todd Goldenbaum wrote:Hello,
I'm trying to find the difference betwen two datetime objects, but I'm getting some unexpected results. I start with two dates out of mysql (code simplified a bit for this example):
my $start_date = DateTime::Format::MySQL->parse_date( '2005-01-05' ); my $end_date = DateTime::Format::MySQL->parse_date( '2005-01-23' );
Then I use one of these two techniques to perform the subtraction:
my $duration = $start_date->delta_days( $end_date );
my $duration = $end_date - $start_date;
Expecting to get a $duration of 18 days. But with either technique, the resulting $duration->days value is 4 instead of the expected 18. And when I ask for $duration->hours, it gives me 0.
Further experimentation with the two dates involved reveals that subtracting two dates that are within a few days of each other seems to work, but at a certain point it breaks down and gives erroneous results. Any idea what could be going on here?
Thanks, ToddThere are a couple of ways to do this; use strict; use warnings; use DateTime; use DateTime::Format::MySql;
my $start_date = DateTime::Format::MySQL->parse_date( '2005-01-05' ); my $end_date = DateTime::Format::MySQL->parse_date( '2005-01-23' );
my $dur = $end_date->delta_days( $start_date ); print $dur->delta_days;
gives the correct result of 18
or
using your example above
my $duration = $end_date - $start_date; print $duration->in_units('days'); gives the same results.
I see now, that did the trick. My mistake was assuming that $duration->days would give the same result as $duration->delta_days( $start_date ) or $duration->in_units('days').
I'm curious now though, what >is< $duration->days used for, if not for expressing the length in days of a $duration?
Todd