使用PHP将小时和分钟转换为分钟

时间:2017-09-22 06:53:48

标签: php google-api

我正在使用Google Maps API来获取两点之间的持续时间。该API以小时和分钟为单位给出持续时间。所以我希望它只使用PHP代码转换为几分钟。有没有解决方案?

Ex:2小时10分钟(应该给出130分钟作为输出)

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

    // Transform hours like "1:45" into the total number of minutes, "105". 
function hoursToMinutes($hours) 
{ 
    $minutes = 0; 
    if (strpos($hours, ':') !== false) 
    { 
        // Split hours and minutes. 
        list($hours, $minutes) = explode(':', $hours); 
    } 
    return $hours * 60 + $minutes; 
} 

// Transform minutes like "105" into hours like "1:45". 
function minutesToHours($minutes) 
{ 
    $hours = (int)($minutes / 60); 
    $minutes -= $hours * 60; 
    return sprintf("%d:%02.0f", $hours, $minutes); 
}  

Src:laserlight - > http://board.phpbuilder.com/showthread.php?10342598-quot-Convert-quot-hours-minutes-quot-to-quot-total_minutes-quot-and-back-quot

答案 1 :(得分:0)

感谢帮助人员,我找到了另一个解决方案......这对我有用

$duration = "What Ever the time (2 hours 10 mins)"

$split = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $duration, -1, PREG_SPLIT_NO_EMPTY);

    if ($split[0] >= 1 && $split[0] < 60 && $split[1] == 'min'){
        $duration = $split[0];
    }
    elseif ($split[0] >= 1 && $split[0] < 60 && $split[1] == 'mins'){
        $duration = $split[0];
    }
    else{
        $durationHours = $split[0]*60;
        $durationMin = $split[2];

        $duration = $durationHours + $durationMin;
        echo $duration;
    }