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,
> Todd
There 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.


However, after checking the docs for this function. I found this:

The C<delta_md> and C<delta_days> methods truncate the duration so
that any fractional portion of a day is ignored.  The C<delta_ms>
method converts any day and month differences to minutes.

Unlike the subtraction methods, B<these methods always return a
positive (or zero) duration>.
^^^^^^^^^^^^^^^^^^^^^^^^^^^
but if I do thisuse 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 = $start_date->delta_days( $end_date );

if ($dur->is_positive) {print "it's positive\n"}
if ($dur->is_negative) {print "it's negative\n"}
print $dur->delta_days;

I get this:
F:\scripts>my.pl
it's negative
-18

Which is correct but does not match what the docs say.
Anyway I hope this helps.

Ron Hill



Reply via email to