2013-01-07 93 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对象。并将其转换为存储在数据库中的格式。

相关问题