0

I am trying to make a function to calculate the time difference of two values, but my return in my code below gives me unexpected string, how come?

            var mf_start_time   = "10:30:30";
            var mf_end_time     = "11:10:10";
            function time_interval(mf_start_time,mf_end_time)
            {
                $s = strtotime($start_time);
                $e = strtotime($end_time);
                if ($s < $e)
                {
                    $a = $e - $s;
                }
                else
                {
                    $e = strtotime('+1 day',$e);
                    $a = $e - $s;
                }
                
                $h = floor($a/3600);
                $m = floor(($a%3600)/60);
                $s = $a%60;
                
                return trim(($h?$h.' hour ':'').($m?$m.' minute ':'').($s?$s.' second ':''));
            }

1

2
  • 2
    This looks like javaScript instead of php, what would mean the $s.' second' needs to be $s + ' second' Commented Aug 6, 2021 at 10:44
  • The methods used within the time_interval function, such as trim, floor and strtotime are PHP methods so the concatenation method would be the period (.) rather than plus sign(+) Commented Aug 6, 2021 at 10:57

1 Answer 1

1

You do appear to be getting the syntax of Javascript and PHP mixed up. There is no var in PHP - that belongs in Javascript and variables in PHP begin with $

A few minor tweaks to your code:

$mf_start_time   = "10:30:30";
$mf_end_time     = "11:10:10";

function time_interval($mf_start_time,$mf_end_time)
{
    $s = strtotime($mf_start_time);
    $e = strtotime($mf_end_time);
    if ($s < $e)
    {
        $a = $e - $s;
    }
    else
    {
        $e = strtotime('+1 day',$e);
        $a = $e - $s;
    }
    
    $h = floor($a/3600);
    $m = floor(($a%3600)/60);
    $s = $a%60;
    
    return trim(($h?$h.' hour ':'').($m?$m.' minute ':'').($s?$s.' second ':''));
}

echo time_interval($mf_start_time,$mf_end_time);

Yields:

39 minute 40 second
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.