PHP – Creating time duration

I am trying to create a duration time.

I have a user option to enter a time duration in any of these formats: 0.5, 1, 1.5, 2, 2.5 ect.

Read More

I have a WordPress post date (used as a start time) and the finish time is calculated with the above user inputs. Together they build a duration time.

Example:

A user enters 1 – Example Out: Duration: 16:30 – 17:30

Problem:

This currently cannot output the correct end time if a user enters anything other then a whole number.

So, 1,2,3 ect would work fine, but 0.5, 1.5, 2.5 will all error and show the wrong end time.

I am need of a second pair of eyes, I cannot see the error of my ways.

    // Get user duration option - 0.5, 1, 1.5, 2 ect
    $course_hours = floatval(get_field('hours'));
    $course_minutes = ($course_hours % 1) * 60;

    $end_hour = intval(get_the_date('H'));
    $end_minute = intval(get_the_date('i'));
    $end_ampm = get_the_date('a');

    if($course_minutes != 0 && $course_minutes + $end_minute <= 59){
        $end_minute += $course_minutes;
        $end_hour += floor($course_hours);
    }
    elseif($course_minutes != 0 && $course_minutes + $end_minute > 59){
        $end_minute = ($course_minutes + $end_minute) % 60;
        $end_hour += floor($course_hours) + 1;
    }
    elseif($course_minutes == 0){
        $end_hour += floor($course_hours);
        if ($end_minute == 0){$end_minute = '00';}
    }

    $end_time = $end_hour.':'.$end_minute;
    $safe_post_status = get_post_status();

    //Demo output
    echo the_date('d F Y G:i'); 
    echo ' - '.$end_time;

Thanks!

Related posts

Leave a Reply

1 comment

  1. Writing logic for your question. Change the date format as per your requirement.
    seems like you are using wordpress.

        $course_hours = (get_field('hours'));
        $course_minutes = ($course_hours) * 60;
        $formatter = [];
        $increment = 0.5;
        $h = $increment * 60;
        while ($h < $course_minutes ) {
    
            $key = date('H:i', strtotime(date('Y-m-d') . ' + ' . $h . ' minutes'));
            $value = date('h:i', strtotime(date('Y-m-d') . ' + ' . $h . ' minutes'));
            $formatter[$key] = $value;
            $h = $h + ($increment * 60 );
        }
        echo $output = implode(" - ",$formatter);
        // 12:30 - 01:00 - 01:30 - 02:00