Perl Date and Time Subtraction Problem

I have a little problem subtracting two datetime objects from each other. I am using the following code:


    $today = DateTime->now( time_zone => 'Europe/Berlin' );

    my $dt1 = DateTime-> new (
                     year => 2011,
                     month => 08,
                     day   => 08,
                     hour => 1,
                     minute => 0,
                     second => 4,
                     time_zone =>'Europe/Berlin'
                     );

    print "DT1 : $dt1\n";
    print "today: $today\n";

    my $sub = $today->subtract_datetime($dt1);

    print "sub days: ".$sub->days."\n";

The print statement for DT1 still prints:

DT1 : 2011-08-08T01:00:04
today: 2011-08-16T08:34:10

But if after subtracting the value $sub->days, it displays 1 instead of 8 days.

Do I have a subtraction error?

Many thanks for your help.

+5
source share
2 answers

DateTime::Durationnot working as you expected (and I). Check all fields $sub:

DT1 : 2011-08-08T01:00:04
today: 2011-08-16T09:02:11
$sub->years: 0
$sub->months: 0
$sub->weeks: 1
$sub->days: 1
$sub->hours: 8
$sub->minutes: 2
$sub->seconds: 7

The difference between the two dates: 1 week + 1 day , the expected eight days.

, $today->delta_days( $dt1 ). delta_days() , () , .

+5

1 1 . , ,

$dur->in_units('days')

, , . ,

my $dur = $today->delta_days($dt1);
print "sub days: ".$dur->in_units('days')."\n";

PS — 08 - :

Illegal octal digit '8' at a.pl line 7, at end of line
Illegal octal digit '8' at a.pl line 8, at end of line

.

0

All Articles