简体   繁体   English

如果小时,分钟,秒php没有前导零,如何格式化HH:MM:SS时间

[英]How to format HH:MM:SS times if no leading zeros for hours, minutes , seconds php

I have time string coming from an array and I want to add up leading zeros if it is not there for integer values below 10. For example I want 我有一个来自数组的时间字符串,如果小于10的整数值不存在,我想加起来前导零。例如,我想要

this "8:10:12"  to "08:10:12"
this "13:7:14"  to "13:07:14"
this "13:25:6"  to "13:25:06"

I can go for a really messy code with splitting by ":" and so on, But I would like to know if this can be done with clean code by one line. 我可以用“:”等分割来获取真正混乱的代码,但是,我想知道是否可以用一行干净的代码来完成。 Just reply if this cannot be done with single line. 如果单行无法完成此操作,请回复。 I'll do the messy code then. 然后,我将编写凌乱的代码。

Thanks in advance..! 提前致谢..!

You can use php date function date with strtotime 您可以在strtotime使用php date函数date

$str = "8:10:12";
$new_str = date("H:i:s",strtotime($str));
echo $new_str;

DEMO 演示

You can use explode , array_map , sprintf , and implode to make it a one-liner, but it's not pretty. 您可以使用explodearray_mapsprintfimplode使其成为array_map ,但这并不漂亮。

$time = implode(':', array_map(function($num) { return sprintf("%02d", $num); }, explode(':', $time)));

See Formatting a number with leading zeros in PHP for other ways to format a number with leading zeroes. 请参阅用PHP格式化带有前导零的数字,以了解其他格式化带有前导零的数字的方法。

Since that is a non standard time format you will have to parse it manually: 由于这是非标准时间格式,因此您必须手动对其进行解析:

<?php
$data = ["8:10:12", "13:7:14", "13:25:6"];

array_walk($data, function(&$time) {
    preg_match('|^(\d+):(\d+):(\d+)$|', $time, $token);
    $time = (new DateTime())->setTime($token[1], $token[2], $token[3])->format("H:i:s");
});


print_r($data);

The output obviously is: 输出显然是:

Array
(
    [0] => 08:10:12
    [1] => 13:07:14
    [2] => 13:25:06
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM