2

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

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..!

Juliyanage Silva
  • 2,529
  • 1
  • 21
  • 33

3 Answers3

6

You can use php date function date with strtotime

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

DEMO

B. Desai
  • 16,414
  • 5
  • 26
  • 47
2

You can use explode, array_map, sprintf, and implode to make it a one-liner, but it's not pretty.

$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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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
)
arkascha
  • 41,620
  • 7
  • 58
  • 90