Convert from SQL datetime to PHP DateTime using

The variable time_of_last_updatein the database has a type datetime, and all I want to do is really print it in the table (see below), but ideally I would like to know what to do it for, convert it to a DateTime type in PHP, and then use methods on it, such as ->formatetc. Performance:

$time_date = $row['time_of_last_update'];
$time_date->format('Y-m-d H:i:s');

It seems obvious that I came from C #, but I get a “Call to a member function () format for a non-object”, and the casting does not seem to suit me. This seems very simple / general, but I cannot find any examples.

$describeQuery = 'SELECT username, firstname, surname, location, time_of_last_update      FROM location';
$query = sqlsrv_query($link, $describeQuery);

echo '<table>';
echo '<tr><th>Username</th><th>Firstname</th><th>Surname</th><th>Location</th><th>Time of last Update</th></tr>';

while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC))
{
// WANT TO CONVERT time_of_last_update (SQL datetime) to a PHP DateTime variable??

echo '<tr>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['surname'] . '</td>';
echo '<td>' . $row['location'] . '</td>';
echo '<td>' . $row['time_of_last_update'] . '</td>';// RETURNING ERROR "Object of class DateTime could not be converted to string"
}

echo '</table>';
sqlsrv_free_stmt($query);
sqlsrv_close($link);

thank

+4
source share
2 answers

1) , sql DATE_FORMAT:

$describeQuery = 'SELECT username, firstname, surname, location, DATE_FORMAT(time_of_last_update, '%Y-%m-%d %H:%i:%s')      FROM location';

2) , php, , format:

// creating new date object
$date_time = new DateTime($row['time_of_last_update']);

//now you can use format on that object:
$formated_date = $date_time->format('d/m/y H:i');
+1

.

$dt = date_create($row['time_of_last_update']);

echo date_format($dt, 'Y-m-d H:i:s');

Carbon, API DateTime.

0

Source: https://habr.com/ru/post/1536092/


All Articles