MySQL Datetime to PHP date format

By shane
Mon, 2012-07-30 16:39
4 comments

Share with Others

An easy one today. I often have to remind myself of how to convert a MySQL datetime to something a little more usable... a UNIX timestamp.

The strototime version

It is incredibly easy, just use the PHP strtotime function.

$timestamp = strtotime($result->my_datetime);

Now you can print the date in any format you want:

print date("Y-m-d H:i:s", $timestamp);

PHP5 Convert MySQL Datetime to PHP date format

If you are using PHP5, the following should accomplish the same thing.

$dtime = new DateTime($result->my_datetime);
print $dtime->format("Y-m-d H:i:s");

Sometimes we all need a reminder of the simple things.

Comments

This example is exactly what I've been looking for! Only problem is that I don't understand what "my_datetime" is in the first example and this is critical to using the example in my personal code. Can someone explain what this means and how I can apply it to my code?

I'm trying to retrieve a DateTime type variable out of a MySQL DB and capture it in PHP as a DateTime type variable.

The my_datetime just refers to the datetime value pulled out of the database. This example assumes you make a database query to get the value.

Hope that helps.

Hi! great example, got a question, I'm trying to get the seconds between two datetimes for a visit counter, my code is this:

$lastv = strtotime($query->row('last_visit')); // from mysql datetime
$currentv = date("Y-m-d H:i:s");
$seconds = $currentv - $lastv;

if ($seconds > 100) {
// more code
}

but is not working, I want to execute some code if the seconds are > than 100, but I'm missing something, can u help me?.
thanks bro!

Like most of the examples of the internet everyone copy and paste the same. James ask very good question and no answer. Can some one please write all the code with defining this var my_datetime. Thank you!

Post new comment