Loading, please wait...

A to Z Full Forms and Acronyms

How to create a class to add two times in PHP | PHP programs

Jan 19, 2022 PHP, 2141 Views
How to create a class to add two times in PHP | PHP programs

How to create a class to add two times in PHP | PHP programs

We will create a Time class that contains hours, Minutes, and Seconds and then we add two times.

<?php

class Time
{
    // Properties
    private $hours;
    private $minutes;
    private $seconds;

    function SetTime($h, $m, $s)
    {
        $this->hours = $h;
        $this->minutes = $m;
        $this->seconds = $s;
    }

    function PrintTime()
    {
        print ((int)$this->hours . ":" . $this->minutes . ":" . $this->seconds . '<br><br>');
    }

    function AddTimes(Time $T1, Time $T2)
    {
        $this->seconds = $T1->seconds + $T2->seconds;
        $this->minutes = $T1->minutes + $T2->minutes + $this->seconds / 60;;

        $this->hours = $T1->hours + $T2->hours + ($this->minutes / 60);
        $this->minutes %= 60;
        $this->seconds %= 60;
    }
}

$T1 = new Time();
$T1->SetTime(10, 5, 24);

$T2 = new Time();
$T2->SetTime(8, 27, 39);

$T3 = new Time();

$T3->AddTimes($T1, $T2);
print ("Time after addition: ");
$T3->PrintTime();

?>
A to Z Full Forms and Acronyms