Results 1 to 4 of 4
  1. #1

    Adding time to time

    have a duration of an event let's say it's 2 hours 41 minutes.

    I now want to add 30 minutes to it.

    What's the easiest way?

    It's not a time of day, that would be easy but just hours and minutes.

  2. #2

    Adding time to time

    PHP Code:
    <?php

    $minutes
    = 41;
    $hours = 2;

    $add = 30;

    $new_minutes = ($minutes + $add) % 60;
    $new_hours = $hours + floor(($minutes + $add) / 60);

    echo
    "Previous: {$hours} hours, {$minutes} minutes.\n";
    echo
    "Add {$add} minutes.\n";
    echo
    "Current: {$new_hours} hours, {$new_minutes} minutes.";

    ?>


    https://3v4l.org/eYB6R


    -- Cigars, whiskey and wild, wild women. --

  3. #3

    Adding time to time

    Can you explain line 8? What is the % sign doing?

  4. #4

    Adding time to time

    Basically the same as above, but I'd do this:
    PHP Code:
    <?php

    $minutes
    = 41;
    $hours = 2;

    $add = 30;

    $newDuration = ($hours * 60) + $minutes + $add;

    $new_hours = floor($newDuration/60);
    $new_minutes = $newDuration % 60;

    echo
    "Previous: {$hours} hours, {$minutes} minutes.\n";
    echo
    "Add {$add} minutes.\n";
    echo
    "Current: {$new_hours} hours, {$new_minutes} minutes.";


    Convert the time to minutes, add your extension, then convert it back to hours and minutes.

    Adding the extra variable saves doing the math twice and makes the process a bit clearer I think.

    % is called the modulus operator. Essentially it returns the remainder after whole division.

    Comments on this post

    • Sepodati agrees


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •