Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: figuring difference in times?

by BigLug (Chaplain)
on Aug 20, 2005 at 11:12 UTC ( [id://485371]=note: print w/replies, xml ) Need Help??


in reply to figuring difference in times?

I'm one of the DateTime developers, so it may surprise you that in this case I'd wonder if you need the entire swiss army knife that is DateTime, or if all you need is a butter knife...

DateTime can do many things beside simple duration formatting. It can manipulate dates and time and convert them between timezones to most points in history. You can even convert your dates to the Julian calendar or even Tolkien's shire calendar. But if you don't need all that don't bother with DateTime (but think about it carefully, will you be writing some other code in the future to work with these dates? If so, then use DateTime)

The Butter Knife
The following is the non-DateTime way to do it. The math is fairly simple and I've put it into constants so you can follow it easily.

Start with finding out how many of the largest period (weeks) are in the duration, then subtract that from the duration and move to the next level of precision. In the end you'll be left with seconds.

sub doSomethingHere { my $duration = shift; my $MINUTE = 60; my $HOUR = 60 * $MINUTE; my $DAY = 24 * $HOUR; my $WEEK = 7 * $DAY; my $weeks = int($duration / $WEEK); $duration -= $weeks * $WEEK; my $days = int($duration / $DAY); $duration -= $days * $DAY; my $hours = int($duration / $HOUR); $duration -= $hours * $HOUR; my $minutes = int($duration / $MINUTE); my $seconds = $duration - $minutes * $MINUTE; return ($weeks, $days, $hours, $minutes, $seconds); }
(Disclaimer: The above code is not golf. There are more compact ways to do it without declaring the constants, but this is to illustrate the procedure)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-20 15:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found