Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

How to calculate if today is before May 1

by htmanning (Friar)
on Dec 28, 2019 at 22:42 UTC ( [id://11110709]=perlquestion: print w/replies, xml ) Need Help??

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

Monks,

I need to calculate if TODAY is before May 1 every year. I'm not sure how to do this. Would counting the number of days in the year be the way to go or is there an easier way?

Thanks!

  • Comment on How to calculate if today is before May 1

Replies are listed 'Best First'.
Re: How to calculate if today is before May 1
by stevieb (Canon) on Dec 28, 2019 at 22:53 UTC

    The DateTime distribution can help you:

    use warnings; use strict; use DateTime; my ($month, $day) = (5, 1); my $now = DateTime->now; my $year = $now->year; my $known_date = DateTime->new( year => $year, month => $month, day => $day, ); if ($now < $known_date) { # do stuff }

      At 2020-04-30T23:00:00 my local time, it will be considered May 1st by your approach.

      To use local time (or some other time zone), you can use the following approach:

      use DateTime qw( ); ( my $now = DateTime->now( time_zone => 'local' ) ) ->set_time_zone('floating'); my $cutoff_date = DateTime->new( year => $now->year, month => 5, day => 1, time_zone => 'floating', ); if ($now < $cutoff_date) { # do stuff }

      The floating tz is used instead of local since some time zones have days don't have a midnight.

Re: How to calculate if today is before May 1
by johngg (Canon) on Dec 29, 2019 at 15:34 UTC

    You could use the Time::Piece module which has been in the core Perl distribution since 5.10 I believe.

    johngg@shiraz:~/perl/Monks$ perl -Mstrict -Mwarnings -MTime::Piece -E +' my $now = localtime(); my $may = Time::Piece->strptime( qq{@{ [ $now->year() ] }/05/01 00:00: +00}, q{%Y/%m/%d %T} ); say $now->epoch() < $may->epoch() ? q{Before 1st May} : q{After 1st May};' After 1st May

    I hope this is helpful.

    Update:The "false" part of the ternary would more accurately say "On or after 1st May" being pedantic.

    Cheers,

    JohnGG

Re: How to calculate if today is before May 1 -- oneliner
by Discipulus (Canon) on Dec 29, 2019 at 18:16 UTC
    Hello htmanning,

    Dates are delicate things, and you must use care and recommended modules, as already shown.

    But for such a trivial task you can simply check if you are in January-April (months 0-3 in localtime's 4th element in the list form) ie (localtime(time))[4]<=3 to be sure being before 1st of May:

    perl -E "say qq(we are ),(localtime(time))[4]<=3?qq(BEFORE):qq(AFTER), +qq( 1st of May)" we are AFTER 1st of May

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: How to calculate if today is before May 1
by 1nickt (Canon) on Dec 29, 2019 at 14:04 UTC

    Hi, this: "if TODAY is before May 1 every year" is not clear to me.

    • What does "every year" mean?

    • Do you want to compare known dates, or do you want to know the answer at any given moment in time? In other words, will it matter what time it is when you make the calculation, and/or what the time zones are (as shown by ikegami)?

    Thinking about those aspects of your question should help lead to you to right solution.

    • In some cases it is absolutely necessary to instantiate full-blown DateTime objects with floating TZ.

    • In other cases you don't have to worry about TZ (eg if you are comparing dates from two sources you control and you use UTC throughout your system (as you should in most cases)).

    • In still other cases it's enough to compare strings (e.g. if you are comparing two dates that are known to be in the same TZ and are expressed in ISO format):
      my $d2 = "2019-12-29T12:34:56"; my $d1 = "2019-05-01T00:00:00"; say ($d2 lt $d1 ? "before" : "on or after");
      (You can easily get today's date in ISO format with the core module Time::Piece: $now = Time::Piece->new->datetime;)

    Hope this helps!


    The way forward always starts with a minimal test.
      Sorry. You are right that my original question wasn't clear. I need to know if TODAY is between January 1 and May 1. The DateTime suggestions I received here work fine.

      Thanks for all the responses. I get so much help in this forum.

        Your original question ...

        I need to calculate if TODAY is before May 1 every year

        ... and your refined question ...

        I need to know if TODAY is between January 1 and May 1.

        ... define two different time spans. May 1st is excluded in your original requirement, but included in your refined requirement. You should try to get precise, unambiguous requirements before starting to development.

        If I intentionally misinterpret your original requirement, you are asking if today is before every May 1st of every year, and I can simply answer no (i.e. return false) without even looking at the current date or any other input. Simply because today is AFTER last year's May 1st.

        Thinking about your original requirement for a second without intentionally misinterpreting it makes clear that you want to know if the current date is in the first four months of the current year, so your requirement could be implemented by simply checking if the current month is between January and April (see Re: How to calculate if today is before May 1 -- oneliner).

        Your refined requirement asks for either that OR today being May 1st.

        Alexander

        --
        Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Re: How to calculate if today is before May 1
by shmem (Chancellor) on Dec 29, 2019 at 17:05 UTC

    For "today":

    shmem [qwurx] ~> perl -MDate::Parse -E 'say+(str2time("$_-05-01") >= t +ime ? "before" : "after"). " $_-05-01" for qw(2019 2020)' after 2019-05-01 before 2020-05-01 shmem [qwurx] ~>

    Invoking that on 2020-05-01 will give you "after 2020-05-01". For distinguishig "before", "at" and "after" a simple ternary '? :' construct isn't enough.

    For TODAY as a date in any year, just construct the input for st2time() and the TODAY epoch timestamp (use that instead of time above) according to the format of TODAY.

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (1)
As of 2024-04-24 14:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found