tags:

views:

152

answers:

3

I want to round current time to the nearest 15 minute interval.
So if it is currently 6:07, it would read 6:15 as the start time.

How can I do that?

+8  A: 

You can split the time into hours and minutes and then use the ceil function as:

use POSIX;

my ($hr,$min) = split/:/,$time;    
my $rounded_min = ceil($min/15) * 15;

if($rounded_min == 60) {
   $rounded_min = 0;
   $hr++;
   $hr = 0 if($hr == 24); 
}
codaddict
neat, but 12:58 will become 12:60 and not 13:00 :-(
Øyvind Skaar
@Øyvind Skaar: Thanks for pointing. Fixed it now.
codaddict
+7  A: 

The nearest 15 minute interval to 6:07 is 6:00, not 6:15. Do you want the nearest 15 minute interval or the next 15 minute interval?

Assuming it's the nearest, something like this does what you want.

#!/usr/bin/perl

use strict;
use warnings;

use constant FIFTEEN => (15 * 60);

my $now = time;

if (my $diff = $now % FIFTEEN) {
  if ($diff < FIFTEEN / 2) {
    $now -= $diff;
  } else {
    $now += (15*60) - $diff;
  }
}

print scalar localtime $now, "\n";
davorg
`FIFTEEN` is a really bad name for a constant that equals 900. :)
friedo
+3  A: 

An easy solution is to use Math::Round from CPAN.

use strict;
use warnings;
use 5.010;

use Math::Round qw(nearest);

my $current_quarter = nearest(15*60, time());
say scalar localtime($current_quarter);
mscha