Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

What's "Better" DateTime or localtime?

by mmartin (Monk)
on Jul 11, 2013 at 17:17 UTC ( #1043789=perlquestion: print w/ replies, xml ) Need Help??
mmartin has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I was wondering if one method is 'better' then the other...?

I'm using the Date and Time values quite a few times in my script to calculate what is basically a 'start' and
'end' times to be used within another script. Which can be present and/or future date and times...

So is one of these 2 methods below better to use, for any reason, then the other one?
#!/usr/bin/perl use strict; use warnings; use DateTime; ### Method one... Using the DateTime Function: my $date = DateTime->now->set_time_zone('America/New_York'); # Get the individual values of each below: my $month = $date->month(); my $day = $date->day(); my $year = $date->year(); my $min = $date->minute; my $hour = $date->hour; my $sec = $date->second; print "\tMonth --> $month\n"; print "\t Day --> $day\n"; print "\t Year --> $year\n"; print "\t Hour --> $hour\n"; print "\t Min --> $min\n"; print "\t Sec --> $sec\n"; print "\t\n$month/$day/$year $hour:$min:$sec\n\n"; print "####################################\n\n"; ### Method 2: Use the localtime(time) Function: my ($sec1,$min1,$hour1,$day1,$month1,$year1,@rest) = localtime(time); $month1 += 1; # Add one to Month to get actual $year1 += 1900; # Add 1900 to year to get actual print "\tMonth --> $month1\n"; print "\t Day --> $day1\n"; print "\t Year --> $year1\n"; print "\t Hour --> $hour1\n"; print "\t Min --> $min1\n"; print "\t Sec --> $sec1\n"; print "\t\n$month1/$day1/$year1 $hour1:$min1:$sec1\n\n"; ***************** END SCRIPT ***************** _______________________OUTPUT_______________________ Month --> 7 Day --> 11 Year --> 2013 Hour --> 13 Min --> 13 Sec --> 28 7/11/2013 13:13:28 #################################### Month --> 7 Day --> 11 Year --> 2013 Hour --> 13 Min --> 13 Sec --> 28 7/11/2013 13:13:28
Each of those produces pretty much the same result except the Month is Zero-based and the year is
the number of years since 1900 (*i.e. this year == 113, get actual year by "$year += 1900")...

I'm using each piece of the Date and Time variables at some point later on in the script. So I do need
each individual piece of the date and Time vars cause I use them quite a few times in the script.

Any thoughts or suggestions would be much appreciated.

Thanks in Advance,
Matt


Comment on What's "Better" DateTime or localtime?
Download Code
Re: What's "Better" DateTime or localtime?
by runrig (Abbot) on Jul 11, 2013 at 17:22 UTC
    For simple things, I like Time::Piece myself...no need to add one to the month or 1900 to the year. For more complicated things, I'll use DateTime.

    Update: Also, I agree w/jeffa ... (strptime/strftime)++ !!

      Hey runrig, thanks for the quick reply!

      That's cool, I haven't seen that one before... I just checked its Perldoc out (http://perldoc.perl.org/Time/Piece.html) and
      it seems simple enough. Might be good to give that a try...


      Hummm.... Just thought of something as I'm writing this.
      Once I'm finished with my script I will be porting it to a windows executable using something like "pp" or "CavaPackager". Currently
      I'm writing the script on MY laptop which is linux.

      So what I was just thinking now is that since the use of localtime does NOT require you to include a Module to use it, would
      it be better to use that one in that case? Since things like CavaPackager will include the needed Modules in order to execute the
      script? Does that make sense?

      Again, thanks for the reply, much appreciated.

      Thanks Again,
      Matt

      Humm... Looking at the Synopsis of the Time::Piece Module again I noticed it also uses localtime.

      So since it uses "localtime" does that mean when you include the Module, that it actually modifies what
      localtime will output..?


      Thanks Again,
      Matt

        So since it uses "localtime" does that mean when you include the Module, that it actually modifies what localtime will output?

        By default, yes, it exports and overrides localtime. If you don't want to do that, you can import nothing:

        use Time::Piece qw();
        If I do want to override localtime, I will usually explicitly import it:
        use Time::Piece qw(localtime);
Re: What's "Better" DateTime or localtime?
by sundialsvc4 (Monsignor) on Jul 12, 2013 at 04:54 UTC

    Maybe a “better” question is:   What, exactly, does “better” mean to you ... given this particular situation ... and why?

    This, actually, is not a rhetorical question ...

    On the one hand, we all are paid to make our customers” problems (and ours ...) “just go away.”

    Yet, we must always add to that ... “for good.”

    “We are professionals.   (?)   Do not try this at home.”

    You have, so far, written two apparently-equivalent solutions to the same problem.   If that problem will never, ever, re-appear (courtesy of The Marketing Department™...?) in some out-of-the-blue variation that now makes you, having spent X irrecoverable weeks of your life (successfully...?) “solving” the problem in the first way, now be flagellating yourself that you did not instead use the second ...

    ... “then, Pilgrim, you may count yourself Very Lucky.™   And, Very Rare.™”

    Yet it does happen ... both ways.   Heads.   Tails.   Use your best, most suspicious, most cynical skeptical judgment.   And, good luck to ye.

      Your a poet and you didn't even know it....

      I really just wanted people's opinion on what they liked using "better"...

      I decided to use the localtime method/function (*whichever its called) along with the Time::Piece Module.
      I found that Module had lots of useful Methods with it. Some that I used include:
          *If $t contains 'localtime', then...
              - $t->sec;
              - $t->min;
              - $t->hour;
              - $t->mon;
              - $t->mday;
              - $t->wday;
              - $t->year;
              - $t->mdy("/");

      Those were just some of the Methods I found useful when I was writing my script. I'm sure the other Module/Function has
      plenty of similar Methods along with them. But I just found that this one was a bit more useful for myself...


      Thanks,
      Matt


        One thing to watch out for is daylight savings conversions when adding/subtracting days. E.g., this may not work as expected, depending on what day and what time of day it is run (just as if using the builtin localtime):
        use Time::Piece qw(localtime); use Time::Seconds qw(ONE_DAY); my $t = localtime; my $yesterday = $t - ONE_DAY(); my $tomorrow = $t + ONE_DAY(); print "Today: ", $t->ymd(),"\n"; print "Yesterday: ", $yesterday->ymd(),"\n"; print "Tomorrow: ", $tomorrow->ymd(),"\n";
        I have found this sort of mistake in someone's code before (though the code did not use Time::Piece, just plain localtime). One way to be sure of adding or subtracting the correct number of days would be to truncate to the beginning of the day, then add an extra half day, or subtract a half-day less:
        my $t = localtime->strptime(localtime->ymd(), '%Y-%m-%d'); my $yesterday = $t - ( 0.5 * ONE_DAY() ); my $tomorrow = $t + ( 1.5 * ONE_DAY() ); print "Today: ", $t->ymd(),"\n"; print "Yesterday: ", $yesterday->ymd(),"\n"; print "Tomorrow: ", $tomorrow->ymd(),"\n";
        One advantage of DateTime is that it does make it a little easier to get this correct. E.g. in my timezone:
        my $t = localtime->strptime('2013-03-11', '%Y-%m-%d'); my $yesterday = $t - ONE_DAY(); my $tomorrow = $t + ONE_DAY(); print "Today: ", $t->ymd(),"\n"; print "Yesterday: ", $yesterday->ymd(),"\n"; print "Tomorrow: ", $tomorrow->ymd(),"\n"; #Prints: Today: 2013-03-11 Yesterday: 2013-03-09 Tomorrow: 2013-03-12

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (11)
As of 2014-07-14 09:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (257 votes), past polls