Micard
Micard

Reputation: 389

How to concatenate timestamp in php received from the database?

So I have a timestamp from mysql database in a format: 2016-08-15 15:35:53

I receive it like this: $row['date'] and I want to have just 15:35 for example, i.e. HH:MM format. Would be even better if it were a 12-hour format.

I assume it is passes the whole timestamp as a string?

Thank you!

Upvotes: 0

Views: 368

Answers (2)

Marc B
Marc B

Reputation: 360762

Why not do it in MySQL directly? strtotime is a handy function, but it's also a waste of CPU resources, as you'll be forcing mysql and PHP to take the mysql internal datetime value, format it to a string, which you then convert to a php unix timestamp, and then convert BACK to string.

Just do the conversions ONCE:

SELECT time(yourfield) FROM ...
SELECT DATE_FORMAT('%H:%i', yourfield) FROM ...

Relevant docs: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

Upvotes: 1

Micard
Micard

Reputation: 389

Solved with:

$time = date('H:i', strtotime($row['date']));

I don't know if I should delete the question... Thanks splash58

Upvotes: 0

Related Questions