如何在php中格式化小时?

如何在php中格式化小时?,php,format,hour,Php,Format,Hour,我制作了这个函数,它可以工作: $myHour = "09:09"; $myHour = time_format($myHour); function time_format($h){ $initial_string = $h; $new = substr($h,1,strlen($h)); $h = substr($h,0,-4); if ($h == "0"){

我制作了这个函数,它可以工作:

$myHour = "09:09";
$myHour = time_format($myHour);
      function time_format($h){   
            $initial_string = $h;
            $new = substr($h,1,strlen($h));
            $h = substr($h,0,-4);
            if ($h == "0"){
                return $new;
            }else{
                return $initial_string;
            }
        }
此函数验证字符串是否为“01:02”,并去掉第一个“0”,因此它将变为“1:02”,否则,如果它为“13:13”,它将返回“13:13”。
我的问题是如何改进我的功能?或者是否有其他更好的方法?thx

使用ltrim只需删除前导0(如果有)。我想有一个原因,你不能只是改变日期格式生成字符串

 function time_format($h){   
       return ltrim($h, "0");
 }
但是更改日期格式是最好的选择

试着先用谷歌搜索

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

来源:在PHP<5.3

中从时间戳创建DateTime这将是缩短的函数,仍然可读

function time_format($h){
    if (substr($h, 0, 1) == "0"){
        return substr($h, 1);
    }else{
        return $h;
    }
}
这会更短

function time_format($h){
    return substr($h, 0, 1) == "0" ? substr($h, 1) : $h;
}
这一个甚至没有if操作符


要了解更多信息,这里有一个。

几乎可以肯定有一个更好的方法:$h从何而来?$myhour=time_格式($myhour);//$例如,myhours看起来像“04:00”,那么$myhours是从哪里来的呢?现在再看看我的帖子吧,一年没有几天,等等,对于Instance 34:42(34小时42分钟),我有小时和分钟。问题发生在我有“09:05”时,我想去掉第一个“0”,所以结果应该是9:05(9小时5分钟),然后是
newdatetime('34:42:00')
。请阅读手册。(我不知道它是否能工作超过24小时,现在无法测试)。如果不使用
setTime()
I重写我的函数:函数时间格式($h){//se scoate primul“0”din ora a.I 01:21 devine 1:21$initial\u string=$h;$h=substr($h,0,-4);If($h==“0”){return ltrim($initial\u string,“0”)}return$initial\u string;}
function time_format($h){
    return substr($h, 0, 1) == "0" ? substr($h, 1) : $h;
}