如何使用PHP将数字转换为小时和分钟?

时间:2014-02-27 11:58:41

标签: php

我正在尝试将数字转换为小时,分钟。但它不能正常工作。 我有变量,其值类似于

$t_hr = 193;

我希望将其显示为3 hr 13 min 我试过这段代码

$t_min = 193;
if($t_min>60)
   {
    $t_hr=$t_hr+1;
    $t_min = $t_min-60;
   }

效果不好。我需要得到如上所述的价值。任何想法?

3 个答案:

答案 0 :(得分:5)

只需尝试这样

echo floor($t_hr/60)." hr ".($t_hr%60)." min";

假设$t_hrminutes

答案 1 :(得分:0)

首先,您必须确定小时数。这可以通过分工轻松完成:

$t_hr = floor($t_min / 60); // floor(193 / 60) = floor(3.2166...) = 3

然后,您可以使用modulo(返回除法的其余部分)来获得分钟数:

$t_min = $t_min % 60; // 193 % 60 = 13

答案 2 :(得分:0)

这是我的time_format()函数,基于多年前其他人的工作

function time_format($seconds, $mode = "long", $extra = ''){
    $names    = array('long' => array("year", "month", "day", "hour", "minute", "second"), 'short' => array("yr", "mnth", "day", "hr", "min", "sec"));

    $seconds  = floor($seconds);

    $minutes  = intval($seconds / 60);
    $seconds -= ($minutes * 60);

    $hours    = intval($minutes / 60);
    $minutes -= ($hours * 60);

    $days     = intval($hours / 24);
    $hours   -= ($days * 24);

    $months   = intval($days / 31);
    $days    -= ($months * 31);

    $years    = intval($months / 12);
    $months  -= ($years * 12);

    $result   = array();
    if ($years)
        $result[] = sprintf("%s%s %s%s", number_format($years), ' '.$extra, $names[$mode][0], $years == 1 ? "" : "s");
    if ($months)
        $result[] = sprintf("%s%s %s%s", number_format($months), ' '.$extra, $names[$mode][1], $months == 1 ? "" : "s");
    if ($days)
        $result[] = sprintf("%s%s %s%s", number_format($days), ' '.$extra, $names[$mode][2], $days == 1 ? "" : "s");
    if ($hours)
        $result[] = sprintf("%s%s %s%s", number_format($hours), ' '.$extra, $names[$mode][3], $hours == 1 ? "" : "s");
    if ($minutes && count($result) < 2)
        $result[] = sprintf("%s%s %s%s", number_format($minutes), ' '.$extra, $names[$mode][4], $minutes == 1 ? "" : "s");
    if (($seconds && count($result) < 2) || !count($result))
        $result[] = sprintf("%s%s %s%s", number_format($seconds), ' '.$extra, $names[$mode][5], $seconds == 1 ? "" : "s");

    return implode(", ", $result);
}

echo time_format(193),'<br />';
echo time_format(193, 'short'),'<br />';
echo time_format(193, 'long', 'special'),'<br />';

应该返回:
3小时13分钟 3小时13分钟 3小时特别,13分钟