Andrew
Andrew

Reputation: 239197

PHP: Best way to convert a datetime to just time string?

I have a datetime that I pulled from the database that looks like this: 2000-01-01 08:00:00

Now I need to convert it so all I have left is: 08:00:00

What is the best way to do this?

Upvotes: 0

Views: 5529

Answers (5)

Amr Ezzat
Amr Ezzat

Reputation: 401

You can use date and enter the needed time format after parsing timestamp to str

date('h:i a', strtotime('2000-01-01 08:00:00'))

Upvotes: 0

Andrew
Andrew

Reputation: 239197

I should have thought of this earlier...easiest way would be to use the MySQL TIME() function to only select the time in the first place.

Upvotes: 1

Bob Baddeley
Bob Baddeley

Reputation: 2262

you can also use the php strtotime function to turn it into a datetime object, then use the format method on it to get a pretty representation however you want. That way you can put in am/pm, do 24 hour or 12 hour, do whatever you want with the date, etc.

$date = strtotime('2000-01-01 08:00:00');
echo $date->format('H:i:s');

Upvotes: 1

Jack
Jack

Reputation: 1386

You could use

substr($timestamp, -8);

Upvotes: 4

ajreal
ajreal

Reputation: 47331

substr('2000-01-01 08:00:00', 11);

Upvotes: 4

Related Questions