Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Round time to nearest 15 or 30 minutes

by atcroft (Abbot)
on Apr 25, 2006 at 03:52 UTC ( #545458=note: print w/replies, xml ) Need Help??


in reply to Round time to nearest 15 or 30 minutes

Just how tied to the hash are you? Assuming you have a function call such as: myfunc($ts, $interval), then something like the following might also be worth considering:

sub myfunc { my ($ts, $interval) = @_; my $minute; # # Somehow get $minute from $ts, # using the method of your choice. # # Ex., using the method in the OP... $minute = substr($ts, 10, 2); return $interval * int($minute / $interval); }
as it appears to provide the same results you seek, but perhaps with a little less brain-damage....

Hope that helps.

Replies are listed 'Best First'.
Re^2: Round time to nearest 15 or 30 minutes
by jesuashok (Curate) on Apr 25, 2006 at 04:02 UTC
    Hi

    Thanks a lot.
    definitely I have to improve my logical Ideas.
    That is working fine as expected.

    "Keep pouring your ideas"
      If you want the nearest 15 minute boundary, then the code is wrong. It will give you the previous 15 minute boundary.

      You need to:

      • add $interval/2 minutes to the time;
      • subtract the remainder you'd get when dividing by $interval minutes.

      Note that the modulus operator % only works with integers. In practice, you can probably ignore the fraction of a minute that gets thrown away. If you can't, then you'll need to write your own remainder function.

        Ah, this was very helpful, thanks. Not being too clever in these matters, I didn't quite understand the above, but it got me close enough to experiment successfully (though I don't quite get the second bullet item). In my case I was after an offset to add to a unixtime, so that's how the code is oriented.
        for (my $i = 0; $i < 60; $i++) { my $offset = getOffsetToNearestInterval($i,15); print "$i: " . ($i + $offset) . ' (' . $offset . ')' . "\n"; } sub getOffsetToNearestInterval { my $number = shift; my $interval = shift; my $nearest_interval = ( $interval * int( ($number + ($interval/2) + ) / $interval) ); my $offset_to_interval = $nearest_interval - $number; return $offset_to_interval; }
        Hope this helps the next guy stumbling on this thread.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2020-05-27 03:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (152 votes). Check out past polls.

    Notices?