Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Determining time since

by duff (Parson)
on Jan 12, 2004 at 15:03 UTC ( [id://320673]=note: print w/replies, xml ) Need Help??


in reply to Determining time since

I have a few of comments:

  • You shouldn't stringify your numbers. $elapsed > 3600 works just fine thanks.
  • You should separate your "chopping up time" logic from your presentation logic. I'd write a subroutine that does what you need to an elapsed-time value and returns an array of seconds, minutes, hours, etc.
  • Have you checked CPAN? I'm fairly sure there's already a module that does this (though I've not had occasion to use it).

As to a better way than your method, you might want to use integer division and modulo arithmetic:

$days = int($time/86400); $time %= 86400; # leave only the part that's less than a d +ay $hours = int($time/3600); $time %= 3600; # leave only the part that's less than an +hour; ... # and so on

Replies are listed 'Best First'.
Re: Re: Determining time since
by l2kashe (Deacon) on Jan 12, 2004 at 15:45 UTC

    Along the same lines, you could do something to the effect of

    Update: After reading sulfericacid's response, I tested my algo. The issue was a typo ( popped up with use strict;), and I wasn't calling int. New code below.

    #!/usr/bin/perl # tested and verified use strict; my $then = time() - (86400 * 3); my $min_s = 60; my $hour_s = $min_s * 60; my $day_s = $hour_s * 24; my $elapsed = time() - $then; my $output; my $days = int( $elapsed / $day_s ); $elapsed -= $days * $day_s; $output = "$days days " if $days; my $hours = int ( $elapsed / $hour_s ); $elapsed -= $hours * $hour_s; $output .= "$hours hours " if $hours; my $mins = int ( $elapsed / $min_s ); $elapsed -= $mins * $min_s; $output .= "$mins minutes " if $mins; $output .= "$elapsed seconds" if $elapsed; # so on and so forth; print "$output ago\n";

    use perl;
    Everyone should spend some time pounding nails with their forehead for a while before they graduate to complicated stuff like hammers. - Dominus

      I tried l2kashe's code and the test came out:
      0.00146257716049383 days 4.21062361931911e-18 hours ago
      I have no idea what went wrong, but I think you should go with a module on this one. Check out Time::Duration from cpan.org. It looks like it'll accomplish this for you.


      "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

      sulfericacid

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-24 01:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found