Someone
Someone

Reputation: 10575

How do i format time in php

I have a time returned from database in php as 92500. But i want to format the time as 09:25 how can do this echo date ('H:i',strtotime($row['time'])) .it is outputting 00:00. How can i get 09:25

Upvotes: 18

Views: 48128

Answers (6)

sfg2k
sfg2k

Reputation: 149

public static function formatSeconds($secs=0){
    $units = array('Sec', 'Min', 'Hrs', 'Days', 'Months', 'Years'); 
    if($secs<60){
        $time=$secs;
        $pow=0;
    }
    else if($secs>=60 && $secs<3600){
        $time=$secs/60;
        $pow=1;            
    }
    else if($secs>=3600 && $secs<86400){
        $time=$secs/3600;
        $pow=2;            
    }
    else if($secs>=86400 && $secs<2592000){
        $time=$secs/86400;
        $pow=3;            
    }
    else if($secs>=2592000 && $secs<31104000){
        $time=$secs/2592000;
        $pow=4;            
    }
    else if($secs>=31104000 ){
        $time=$secs/31104000;
        $pow=5;            
    }

    return round($time) . ' ' . $units[$pow]; 
}

Upvotes: 1

Rajat Jain
Rajat Jain

Reputation: 1022

Try this simple function to convert 24 hours time to 12 hour time including "AM" and "PM"

<?php 
echo change_time("00:10");               // call the change_function("user input here")
?>
function change_time($input_time)
{
// 23:24    
//break time
$hours = substr($input_time,0,2);
$mins = substr($input_time,3,2);

if (($hours >= 12) && ($hours <= 24))
{
    if (($hours == 24))
    {
        $new_hour = "00";
        $part = "AM";
    }
    else {
        $new_hour = $hours - 12;
        $part = "PM";
    }

}
else
{
    //$new_hour = $hours - 12;
$new_hour = $hours;
    $part = "AM";
}


return $new_hour .":" . $mins ." " . $part . "(".$input_time .")";
}

Upvotes: -3

Matthew
Matthew

Reputation: 48304

One of many ways:

$time = '92500'; // HHMMSS

if (strlen($time) == 5)
  $time = '0'.$time;

echo substr($time, 0, 2).':'.substr($time, 2, 2);

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227310

You said `$row['time']` was "number type". Do you mean that it's a timestamp? If so, you don't need `strtotime`.

echo date('H:i', $row['time'])

The value 92500 is not a valid time value for strtotime(). See this page for valid time values.

Upvotes: 0

zod
zod

Reputation: 12437

g 12-hour format of an hour without leading zeros 1 through 12

Use PHP date itself

https://www.php.net/manual/en/function.date.php

Upvotes: 0

Alex Bailey
Alex Bailey

Reputation: 1679

Actually

$date = '9:25';

echo date ('H:i',strtotime($date));

is working perfectly fine for me.

Returns "09:25".

So i guess it has to be some error with your database value meaning $row['time'] doesn't contain the right value.

Upvotes: 27

Related Questions