2013-01-07 61 views
0

我有一個excel工作表,我正在導入,但我希望將一些數據轉換爲分鐘。雖然格式從5h 5m 6.64s6.64s不同,我怎麼能夠將其轉換爲只有在PHP分鐘? (我相信DateTime::createFromFormat()不會工作,因爲它的範圍是從0到59.)如何轉換不同的「h m s」Excel時間格式?

也可以將其轉換爲更簡單的格式,以便在PHP應用程序中操縱和繪製圖形或將其轉換爲某個時間對象PHP類更好?

請記住數據必須格式化,然後導入到MySQL服務器,然後回讀到PHP應用程序進行統計。我也使用cakePHP框架來構建應用程序。感謝您的任何反饋。

回答

1

如果字符串的不同部分總是用空格隔開,你可以簡單地使用:

$timeParts = explode(' ', $timestring); //Separates your time string in parts 
//To sum these parts into a total number of minutes: 
//First make an array with all multiplication factors to go from part of string to a number of minutes 
$factors = array(1/60, 1, 60, 60*24); //Last value is for days, which are probably not necessary. 

//Iterate through the $timeParts array 
$minutes = 0; //Create $minutes variable, so we can add minutes to it for each string part 
while($part = array_pop($timeParts)) { //Process each part of the string, starting from the end (because seconds will always be there even if minutes aren't) 
    $part = floatval($part); //I guess your numbers will technically be strings, so we need to convert them to floats (because the seconds need to be floats). Also, this function should strip off any letters appended to your numbers. 
    $factor = array_shift($factors); //Take the first part of the $factors array (because in that array the seconds are first, then minutes and so on) 
    $minutes += ($part * $factor); //Multiply the string part by its matching factor and add the result to the $minutes variable. 
} 

我沒有測試過這一點,所以你需要自己調試。

+0

全國聯絡謝謝先生! –

2

如果所有時間的格式都是h m s(其中任何一個都是可選的),我認爲提取數字並不難。這可以用一個簡單的正則表達式等來完成:

/(([0-9]{1,2})h)?(([0-9]{1,2})m)?(([0-9]{1,2}\.[0-9]{0,2})s)?/ 

然後,你可以簡單地把這些數字在PHP的DateTime對象。並將其轉換爲存儲在數據庫中的格式。

相關問題