0

I want something that seems simple but can't figure out :

I have an integer which in my program is an hour, in a 24h format (ie '18') and I want to add X (ie '7') hours to it.

How do I add hours to something that is not at date object whatsoever. Something that would work like this :

18 + 7 = 1
5
  • 1
    You could utilize the modulus % operator? (18 + 7) % 24 == 1
    – Blake
    Sep 7, 2016 at 19:42
  • do you need to keep track of how many days this result is, or are you purely interested in the resulting hour value?
    – Marc B
    Sep 7, 2016 at 19:47
  • @MarcB I'd presume he only cares about hours, because he says it's "not [a] date object whatsoever"
    – Blake
    Sep 7, 2016 at 19:47
  • @Blake: doesn't matter. intervals aren't date objects, but there's going to be someone who needs to know that something took 10 days and 1 hour, v.s. only 1 hour.
    – Marc B
    Sep 7, 2016 at 19:48
  • @MarcB I only care about the hour in my case
    – Gunga Din
    Sep 7, 2016 at 19:49

3 Answers 3

1

Using the modulus operator is what you're after. See this example:

echo ((18 + 7) % 24); // Output: 1

0
0

Please use % (modulus) for this.

(18 + 7) % 24 = 1
0

% operator could come to your rescue:

  <?php
    $hour_24_format =18;
    $x_hours = 7;
    define("_TWENTY_FOUR_",24);
     $result = ($hour_24_format + $x_hours)% _TWENTY_FOUR_ ; 
  ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.