RSS

Newsletter

The CodeKarate Newsletter is the best way for technical ninjas to keep their swords sharpened. Don't worry, we won't flood your inbox and your email address will always remain private.
Back to Top

MySQL Datetime to PHP date format

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.

Discussions

1
James (not verified)

Question about example

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.

2
shane

The my_datetime just refers

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.

shane's picture

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h2> <h3> <blockquote> <img>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <css>, <html>, <php>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <mysql>, <python>, <ruby>. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.