4

The variable time_of_last_update in the database is of type datetime, and all I want to do is really print it out in the table (below) but ideally I would like to know for future reference how to cast it/convert it to a DateTime type in PHP, to then use the methods on it such as ->format etc. Doing:

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

Seems obvious to me coming from C#, but I get "Call to a member function format() on a non-object", and casting doesn't seem to hep me either. This seems really simple/common, 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);

Thanks

1
  • What does var_dump($row['time_of_last_update']); output? Commented Apr 11, 2014 at 11:50

2 Answers 2

3

1) If you just want to display date in correct format, then format it in sql by using DATE_FORMAT:

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

2) If you want it as date object in php you need to create it first, before calling method 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');
Sign up to request clarification or add additional context in comments.

Comments

1

See date and time related extensions.

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

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

You should also take a look at Carbon if you need a simple API extension for DateTime.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.