Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Datetime subtraction problem

I've got a little problem by subtracting two datetime objects from each other. I use 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 and today prints:

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

But if I print after the subtraction the $sub->days value it shows 1 instead of 8 days.

Do I have a error in my subtraction?

Many thanks for your help.

like image 664
JohnDoe Avatar asked Aug 16 '11 06:08

JohnDoe


1 Answers

The DateTime::Duration does not work as you (and I) expected. Check all fields of $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 is 1 week + 1 day, the expected eight days.

If you want the difference in days, try $today->delta_days( $dt1 ). The delta_days() method returns a duration which contains only days (edit) and weeks, but not months.

like image 140
Anders Lindahl Avatar answered Sep 24 '22 02:09

Anders Lindahl