perl

A DateTime object can only be compared to another DateTime object


I've got a script that will compare 2 datetime objects, however the error is telling me this:

A DateTime object can only be compared to another DateTime object

I'm not sure why I'm getting this error as both variables are datetime objects. Here's the code.

use strict;
use warnings;
use DateTime;
use DateTime::Format::Strptime;

my $dt = DateTime->now(time_zone=> 'America/New_York');
my $datetoday = $dt->strftime('%Y%m%d');
my $parseseq = DateTime::Format::Strptime->new(pattern => '%Y%m%d');

my $lastwatermark = 20250201;
$lastwatermark = $parseseq->parse_datetime($lastwatermark)->set_formatter($parseseq);
$lastwatermark->add(days => 2);

print "\nlastwatermark is less than datetoday\n" if ($lastwatermark < $datetoday);

exit;

Solution

  • The complete error on my Perl 5.36 add interesting object instance details:

    A DateTime object can only be compared to another DateTime object (DateTime=HASH(0x55b56bc53eb0), 20250221). at l.pl line 16

    I can run your script successfully with this minor edit:

    [...]
    
    # need this to transform object to date string
    $lastwatermark = $lastwatermark->strftime('%Y%m%d');
    
    print "\nlastwatermark is less than datetoday\n" if ($lastwatermark lt $datetoday);