JohnDoe
JohnDoe

Reputation: 163

Subtracting two dates with perl DateTime

I try to subtract two dates from each other but unfortunately without success. Maybe someone could give me a hand. My first try looks like:


#!/usr/bin/perl -w
#use strict;
use warnings;
use DateTime;

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

my $year = '2011';
my $month = '03';
my $day = '22';

my $dt1 = DateTime-> new (
                     year => $year,
                     month => $month,
                     day   => $day,
                     time_zone =>'Europe/Berlin'
                     );

my $mydate = $dt1->ymd;

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

print "subtraction: $sub \n";

Thanks in advance.

Upvotes: 0

Views: 4122

Answers (3)

ikegami
ikegami

Reputation: 385789

->ymd returns a string, not a DateTime object.

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

should be

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

or just

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

DateTime

Upvotes: 1

Miguel Prz
Miguel Prz

Reputation: 13792

The problem is that you are calling ymd method, which returns a string, not a DateTime object. So as wk tells you, you should use the subtract_datetime method before calling the ymd method. In your code, you'll probably get the "Can't call method "subtract_datetime" without a package or object reference at ..." message

Upvotes: 0

w.k
w.k

Reputation: 8376

One problem seems to be here:

$today = $today->ymd;

It writes over object, but you want to use it's method later.

Upvotes: 3

Related Questions