2011-12-17 61 views
0

我在定义为mediumint(11)的数据库中有一个值。目前它返回3600如果我运行查询。从数据库转换时间

这个函数在这里应该将该值转换为:1小时。但是,当我运行该功能时不会。我没有任何价值。

function strTime($s) { 
    $d = intval($s/86400); 
    $s -= $d*86400; 

    $h = intval($s/3600); 
    $s -= $h*3600; 

    $m = intval($s/60); 
    $s -= $m*60; 

    if ($d) $str = $d . 'd '; 
    if ($h) $str .= $h . 'h '; 
    if ($m) $str .= $m . 'm '; 
    if ($s) $str .= $s . 's'; 

    return $str; 
} 

很基本,必须是db中的值吗?调用此(的Joomla特定)

代码:

$query = "SELECT streaming_limit FROM #__cc_users WHERE user_id=".$user->id; 
$db->setQuery($query); 
$steaming_limit = $db->loadResult(); //returns 3600 
echo strTime($streaming_limit); //returns nothing 
+1

我有一种感觉,有一个问题,在某个地方,哪来的*问题*? – 2011-12-17 21:35:02

+0

那究竟是什么问题?你目前的输出是多少?换句话说:我们能在什么时候帮助你? ;-) – 2011-12-17 21:36:40

+0

哎呀,添加了编辑。基本上这个函数不会像我期望的那样返回1小时,而是会得到一个空值。 – Tom 2011-12-17 21:37:14

回答

1

执行此操作的更强大的方法是PHP的DateTimeDateInterval类,它们专门用于这类事情。 下面的代码创建两个DateTime对象,将指定的秒数 添加到一个对象,然后计算两者之间的间隔。

在这一点上,你可以格式化时间差,但是你会喜欢用DateInterval::format

function strTimeDiff($seconds) 
{ 
    $date1 = new DateTime(); 
    $date2 = new DateTime(); 
    $date2->add(new DateInterval('PT'.$seconds.'S')); 
    $interval = $date1->diff($date2); 

    echo $interval->format('%d days, %h hours, %i minutes, %s seconds'); 
} 

$secs_from_db = 3600; 
echo strTimeDiff($secs_from_db); 
// 0 days, 1 hours, 0 minutes, 0 seconds 
+0

thx的细节 – Tom 2011-12-18 02:02:57

0

你可以尝试使用这样的事情:

“转换的秒数含小时,分别分,秒的数组”

http://codeaid.net/php/convert-seconds-to-hours-minutes-and-seconds-%28php%29

<?php 

/** 
* Convert number of seconds into hours, minutes and seconds 
* and return an array containing those values 
* 
* @param integer $seconds Number of seconds to parse 
* @return array 
*/ 
function secondsToTime($seconds) 
{ 
    // extract hours 
    $hours = floor($seconds/(60 * 60)); 

    // extract minutes 
    $divisor_for_minutes = $seconds % (60 * 60); 
    $minutes = floor($divisor_for_minutes/60); 

    // extract the remaining seconds 
    $divisor_for_seconds = $divisor_for_minutes % 60; 
    $seconds = ceil($divisor_for_seconds); 

    // return the final array 
    $obj = array(
     "h" => (int) $hours, 
     "m" => (int) $minutes, 
     "s" => (int) $seconds, 
    ); 
    return $obj; 
} 
+0

这有完全相同的问题......所以这不会作为解决方案。 – Tom 2011-12-18 01:19:53