Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:如何将秒格式化为这个日期字符串格式?_Php_Date_Datetime - Fatal编程技术网

PHP:如何将秒格式化为这个日期字符串格式?

PHP:如何将秒格式化为这个日期字符串格式?,php,date,datetime,Php,Date,Datetime,我有一个php变量,$seconds=秒数。 我想将此值转换为字符串格式:'xxh xxmin xxs'其中xx是值,如果为空则不显示 我目前使用的代码如下,效果良好: $hours = floor($seconds/3600); $seconds -= $hours * 3600; $minutes = floor($seconds/60); $seconds -= $minutes *60; $string=''; if ($hours) $string .= $hours . 'h';

我有一个php变量,
$seconds=秒数。

我想将此值转换为字符串格式:
'xxh xxmin xxs'
其中xx是值,如果为空则不显示

我目前使用的代码如下,效果良好:

$hours = floor($seconds/3600);
$seconds -= $hours * 3600;
$minutes = floor($seconds/60);
$seconds -= $minutes *60;

$string='';
if ($hours) $string .= $hours . 'h';
$string = $string ? $string . ' ' : $string;
if ($minutes) $string.= $minutes .'min';
$string = $string ? $string . ' ' : $string;
if ($seconds) $string .= $seconds . 's';

return trim($string);
有没有一种直接的方法可以让gmdate做到这一点?以下内容在null时保留值,而不是我要查找的值

gmdate('H\h i\m\i\n s\s', $duration) : '';
只需创建一个对象,将其设置为
00:00:00
,然后您就可以添加秒数,如下所示:

<?php

    $seconds = 350;

    $date = new DateTime("00:00:00");
    $date->modify("+ $seconds seconds");
    echo $date->format("H:i:s");

?>
编辑:

如果不想在值为0时显示该值,则只需使用以下命令:

echo implode(" ", array_filter(explode(":", $date->format("H\h:i\m\i\\n:s\s")), function($v){return $v != 0;}));
输出:

00:05:50
05min 50s

如果你在做大量的时间操作,你可能会从No中得到很好的使用,因为使用
gmdate()
没有直接的方法,所以你会被
If
语句“卡住”。你的代码对你有用,为什么要改变它?啊哈,那只是出于好奇。如果我们能解决这个问题的话,我可能会学到更好的方法。现在我仍然坚持我最初的解决方案。我不认为gmdate可以有条件地显示值。
我想把这个值转换成字符串格式:“xxh xxmin xxs”,其中xx是值,如果为空则不会出现。
,所以这基本上是错误的答案。@Glavić然后他可以这样使用:
echo$date->format(“H\H:I\m\n:s\s”)不,这不符合他的需要,因为他说,如果值为零,它不应该显示。@Glavić当值为零时,他在哪里说他不想显示它?可以用gmdate压缩成一行