Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

DateTime days limit

by htmanning (Friar)
on Apr 20, 2020 at 21:12 UTC ( [id://11115846]=perlquestion: print w/replies, xml ) Need Help??

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

Monks, I'm using the following to prohibit reservations being made more than a specified number of days in advance.

if ($fc_days_limit) { use DateTime::Duration (); my $days_from_now = $now->clone->add( days=>$fc_days_limit ); if ($reservation_date > $days_from_now) { #show error } }
This works well, but is too specific to the time. If $fc_days_limit=7 and it is noon and I make a reservation 7 days from now for 11am, it works. If I make it for 1pm, it shows an error. I need to have it triggered only by the date without including the time. I could parse the timestamp but isn't there an easier way to do it?

Replies are listed 'Best First'.
Re: DateTime days limit
by Corion (Patriarch) on Apr 20, 2020 at 21:16 UTC

    I think the easiest approach is to simply compare the date parts:

    if( $reservation_date->ymd gt $days_from_now->ymd ) { ... }
      Perfect!

      Thank you.

Re: DateTime days limit
by haukex (Archbishop) on Apr 20, 2020 at 22:25 UTC

    Sounds like you want DateTime's ->truncate method:

    use warnings; use strict; use DateTime; my $now = DateTime->new(year=>2020,month=>4,day=>21,hour=>12); my @tests = ( DateTime->new(year=>2020,month=>4,day=>27,hour=>13), DateTime->new(year=>2020,month=>4,day=>28,hour=>11), DateTime->new(year=>2020,month=>4,day=>28,hour=>13), DateTime->new(year=>2020,month=>4,day=>29,hour=>11) ); for my $reservation_date (@tests) { my $fc_days_limit=7; if ($fc_days_limit) { my $days_from_now = $now->clone->add( days=>$fc_days_limit ) ->truncate( to => 'day' ); my $res_date_only = $reservation_date->clone ->truncate( to => 'day' ); if ($res_date_only >= $days_from_now) { print "Error on $reservation_date\n"; } else { print "Reservation $reservation_date is ok\n"; } } } __END__ Reservation 2020-04-27T13:00:00 is ok Error on 2020-04-28T11:00:00 Error on 2020-04-28T13:00:00 Error on 2020-04-29T11:00:00
Re: DateTime days limit
by mldvx4 (Friar) on Apr 23, 2020 at 04:32 UTC

    Or maybe the Delta_Days function from Date::Calc would be yet another way.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11115846]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2024-04-24 10:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found