Mike Mengell
Mike Mengell

Reputation: 2398

PHP 15 minute rounding

In PHP I need to do a count of 15 minutes within a number of hours and minutes. But I need it to round down if less or equal to 7 minutes and round up if over 7 minutes.

So I have something like;

$totalHours = 10;
$totalMinutes = 46;

The hours is easy enough to work out the number of 15 minutes;

$totalHours = 10*4;

But the minutes is giving me some grief.

Some examples are;

If Minutes = 7 then answer is 0.

If Minutes = 8 then answer is 1.

If Minutes = 18 then answer is 1.

If Minutes = 37 then answer is 2.

If Minutes = 38 then answer is 3.

I would be really grateful if someone could do me a nice function for this. A signature of (int TotalHours, int TotalMinutes) would be great.

Thanks, Mike

Upvotes: 1

Views: 728

Answers (4)

anubhava
anubhava

Reputation: 785058

Try this code:

<?php
echo round($n/15);
?>

// where n is your minute number i.e. 7, 8, 18, 37, 38 etc

Upvotes: 2

nickf
nickf

Reputation: 546025

To round to the nearest X: Divide by x, round to nearest int, multiply by x.

$nearest = round($minutes / 15) * 15;

But in your case, if you just want a count of that, you can simply skip the last step.

$numberOfQuarterHours = round($minutes / 15);

Upvotes: 1

DKSan
DKSan

Reputation: 4197

You could try modulo operation.

PHP.net MOD

Just divide by 15 and get the remaining part. There you could apply test for 7 < x < 8

Upvotes: 0

Antti Huima
Antti Huima

Reputation: 25522

Calculate the number of minutes as (60 * hours + minutes), then add 8, divide by 15, and truncate the result by a call to int().

Upvotes: 1

Related Questions