DateTime convert from database

Hello everybody,

Could someone help me please ? I need to get this DateTime format ‘31-12-2015’ from this DateTime format ‘2015-12-31 23:59:59’.

I tried this code but it did not work.

        // $date1 = '2015-12-31 23:59:59';
        $date2 = DateTime::createFromFormat('d-m-Y H:i:s', $date1);
        $date2->format('d-m-Y');
        echo $date2
echo date('d-m-Y', strtotime($date1));
1 Like
    // $date1 = '2015-12-31 23:59:59';
    $date2 = DateTime::createFromFormat('d-m-Y H:i:s', $date1);
    echo $date2->format('d-m-Y');

but if this comes form the DB it would be easier to do:

SELECT
    DATE_FORMAT(the_date, '%d-%m-%Y') AS the_date,
    …
1 Like

I used this solution

SELECT
DATE_FORMAT(the_date, ‘%d-%m-%Y’) AS the_date,

And it solved my problem. Thank you very much guys.

I’d not recommend this solution as it really slows query down
Good practice is to avoid SQL functions where it’s possible

1 Like

Thank you for your advice. I will try to do so if I have time to do it. Because this query is a little query of 5 rows. Then I don’t think there will be any performance problem with that sql query.

question: which is slower, one SQL function or the PHP functions required to do the same?

EDIT: I’ve tested it with a table containing 64K entries. the difference was ca. 1 ms …

That depends on the query, of course.
SQL functions prevent database from using indexes and that can be a real problem for more complex queries.

so it would only matter, if the converted date were part of the WHERE clause?

Right

so in this particular case it would most probably be faster than the PHP conversion.

In this particular case maybe.
I’m just trying to say that you should be careful with these things.
Performance is not the only aspect.

While you boys argue over which one’s better, i’m just gonna point out that your ‘createFromFormat’ format doesnt match the input. :wink:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.