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. | [reply] [d/l] [select] |
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. | [reply] [d/l] |