Howard Zoopaloopa
Howard Zoopaloopa

Reputation: 3822

Time Bug (My Script) PHP

I've got this weird bug happening. I'm basically just adding a few minutes to a time formatted like '12:20pm' with the following function...

function calc_arb_time($startTime, $amount){
        $startTime = date('Y-m-d') . substr($startTime,0,-2);
        $startTime = strtotime($startTime);


        $seconds = $amount*60;
        $startTime += $seconds;
        $newStartTime = date('g:ia', $startTime);
        return($newStartTime);
    }

echo calc_arb_time('12:20pm',20); // <-- this returns 12:40pm which is great

echo calc_arb_time('1:20pm',20); // this returns 1:40am... Why the AM??

Upvotes: 0

Views: 181

Answers (2)

Mike
Mike

Reputation: 21659

You might also want to look at the DateTime class:

$date = DateTime::createFromFormat('g:ia', '12:20pm');
$date->add(new DateInterval('PT20M'));
echo $date->format('H:i:s');

$date = DateTime::createFromFormat('g:ia', '1:20pm');
$date->add(new DateInterval('PT20M'));
echo $date->format('H:i:s');

Prints:

12:40:00
13:40:00

Upvotes: 0

Alin P.
Alin P.

Reputation: 44346

You're not doing anything to preserve the am or pm part? Also don't worry about the date part if you're not going to use it anyway.

This code is simpler and it works fine:

function calc_arb_time($startTime, $amount){
    $startTime = strtotime('+'.$amount.' minutes', strtotime($startTime));
    return date('g:ia', $startTime);
}
echo calc_arb_time('12:20pm',20).PHP_EOL;
echo calc_arb_time('1:20pm',20);

Also I'm not sure the name of the function reflects what it does. You should consider changing it.

Upvotes: 2

Related Questions