Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I round a date to nearest 15 minute interval in Perl?

Tags:

datetime

perl

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?

like image 503
Bdfy Avatar asked Oct 11 '10 15:10

Bdfy


2 Answers

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); 
}
like image 170
codaddict Avatar answered Oct 28 '22 12:10

codaddict


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_MINS => (15 * 60);

my $now = time;

if (my $diff = $now % FIFTEEN_MINS) {
  if ($diff < FIFTEEN_MINS / 2) {
    $now -= $diff;
  } else {
    $now += FIFTEEN_MINS - $diff;
  }
}

print scalar localtime $now, "\n";
like image 24
Dave Cross Avatar answered Oct 28 '22 13:10

Dave Cross