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

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

How can i do this?

+7
datetime perl
source share
4 answers

You can divide 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); } 
+11
source share

The next 15-minute interval until 6:07 is 6:00, not 6:15. Do you need the next 15 minute interval or the next 15 minute interval?

Assuming this is near, 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"; 
+8
source share

A simple 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); 
+4
source share

Minor change to the first response using sprintf instead of ceil and POSIX. Also does not use any additional CPAN modules. This rounds up or down so 6:07 = 6:00, 6:08 = 6:15, 6:22 = 6:15 and 6:23 = 6:30. Note that an hour is added if the rounded minutes are 60. However, to do this correctly, you will need to use the timelocal and localtime functions to add the hour. that is, adding an hour can add a day, a month or a year.

  #!/usr/bin/perl my ($hr,$min) = split/:/,$time; my $interimval = ($min/15); my $rounded_min = sprintf "%.0f", $interimval; $rounded_min = $rounded_min * 15; if($rounded_min == 60) { $rounded_min = 0; $hr++; $hr = 0 if($hr == 24); } 
0
source share

All Articles