0

I made this function and it works:

$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;
            }
        }

This function verify it the string looks like: "01:02" and get rid of the first "0", so it will become "1:02" else if it looks like "13:13" it will return "13:13". My question is how to improve my function? or if there exists other better method ? thx

Attila Naghi
  • 2,535
  • 6
  • 37
  • 59

4 Answers4

2

use ltrim to just simply remove the leading 0 if there is one. I assume there is a reason you cant just change the date format which generates the string ?

 function time_format($h){   
       return ltrim($h, "0");
 }

But changing the date format is the best option

exussum
  • 18,275
  • 8
  • 32
  • 65
  • I rewrite my function : function time_format($h){ // se scoate primul "0 " din ora a.i 01:21 devine 1:21 $initial_string = $h; $h = substr($h,0,-4); if ($h == "0"){ return ltrim($initial_string, "0"); } return $initial_string; } – Attila Naghi May 19 '14 at 10:30
1
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Please have a detailed look here: http://www.php.net/manual/en/datetime.format.php

You can get a DateTime object by UnixTimestamp (if needed) with this way

$dtStr = date("c", $timeStamp);
$date = new DateTime($dtStr);

Source: Creating DateTime from timestamp in PHP < 5.3

Community
  • 1
  • 1
Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
  • I dont have days year, etc, I have hours and minutes , for instace 34:42 (34 hours and 42 minutes). The problem occurs when i have "09:05" I want to get rid of the first "0" so the result should be 9:05 (9 hours and 5 minutes) – Attila Naghi May 19 '14 at 10:28
  • then it is `new DateTime('34:42:00')`. Please Read the Manual. (I dont know if it works with more then 24 hours, can't test it now). If not use `setTime()` – Christian Gollhardt May 19 '14 at 10:35
1

this will be your shortened function, still readable

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

this would be even shorter

function time_format($h){
    return substr($h, 0, 1) == "0" ? substr($h, 1) : $h;
}

this one is even without the if operators

to read more about it, here is a link.

Friedrich
  • 2,211
  • 20
  • 42
-2

use PHP date function

try to google first..

naveen
  • 87
  • 1
  • 3
  • 10