Skip to content
Advertisement

form type=“time” calculation results in full number only

I’m trying to calculate times from a time input but the result will always be a full number for example 16:45 – 8:30 doesnt result into 8:15 or 8.15 but only 8 and i can’t find a solution to this. Here is the code:

    <?php 
if(isset($_POST['a_submit'])){
    $begin = $_POST['begin'];
    $end = $_POST['end'];
    $test = $end - $begin;
    echo $test;
} ?>

<form class="container mt-5" action="#" method="post">
<div class="form-group row">
            <label for="begin" class="col-sm-4 col-form-label">begin</label>
            <div class="col-sm-8">
                <input type="time" class="form-control-plaintext" id="staticEmail" name="begin">
            </div>
        </div>
        <div class="form-group row">
            <label for="end" class="col-sm-4 col-form-label">end</label>
            <div class="col-sm-8">
                <input type="time" class="form-control-plaintext" id="staticEmail" name="end">
            </div>
        </div>
        <button class="btn btn-primary" name="a_submit" type="submit">go</button>
</form>

Thanks for the help

Advertisement

Answer

You’re subtracting time string values instead use the following code to get the time difference.

$a = new DateTime($_POST['begin']);
$b = new DateTime($_POST['end']);
$b->modify('-1 hours'); // subtract 1 hour break time from endtime
$interval = $a->diff($b);
echo $interval->format("%H:%i");

see here as well Subtract time in PHP

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement