htmanning has asked for the wisdom of the Perl Monks concerning the following question:

Monks, I'm using the following to check for things happening one year from now and one week from now.
use DateTime::Duration (); my $one_year_from_now = $now->add( years=>1 ); if ($reservation_date > $one_year_from_now) { do something } and then use DateTime::Duration (); my $one_week_from_now = $now->add( weeks=>1 ); if ($reservation_date > $one_week_from_now) { do something }
If the one year from now routine happens before the one week from now routine, it cancels out the one week from now routine. It is as if it is resetting NOW and I don't understand why.

Replies are listed 'Best First'.
Re: DateTime issues
by haukex (Archbishop) on Apr 03, 2020 at 20:53 UTC

    I apologize, I initially made an oversight in my reply to your previous question. $now->add( years=>1 ) actually modifies the $now object and returns the same object. Use $now->clone->add(...) to get a modified copy of $now instead.

    Edit: Improved wording.

      Thanks. I'll try that.
Re: DateTime issues
by leszekdubiel (Scribe) on Apr 05, 2020 at 18:44 UTC
    #!/usr/bin/perl -CSDA use utf8; use Modern::Perl; use Time::Piece; use Time::Seconds; my $reservation_date = localtime->strptime("2020-03-15#", "%Y-%m-%d#") +; print "$reservation_date\n"; my $one_year_from_now = $reservation_date->add_months(-12); if ($reservation_date > $one_year_from_now) { printf "%s is after one year earlier from now that is %s\n", $reservation_date->strftime("%Y-%m-%d"), $one_year_from_now->strftime("%Y-%m-%d"), } my $one_week_from_now = localtime() + ONE_WEEK; if ($reservation_date < $one_week_from_now) { printf "%s is before one week from now that is %s\n", $reservation_date->strftime("%Y-%m-%d"), $one_week_from_now->strftime("%Y-%m-%d %H:%M:%S"), }
    result: Sun Mar 15 00:00:00 2020 2020-03-15 is after one year earlier from now that is 2019-03-15 2020-03-15 is before one week from now that is 2020-04-12 20:43:49
      my $reservation_date = localtime->strptime("2020-03-15#", "%Y-%m-%d#") +; my $one_year_from_now = $reservation_date->add_months(-12); if ($reservation_date > $one_year_from_now) {

      That's a confusing name for that variable, and also that comparison will always be true.