开发者

Time Bug (My Script) PHP

开发者 https://www.devze.com 2023-01-28 04:05 出处:网络
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...

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??


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消