Convert DateTime From PHP to MySql Format

When using web technologies PHP and MySql on a web application, you may come across the need to add the current DateTime in your database. A simple way to get the server time in PHP is to use the $_SERVER['REQUEST_TIME'] function. It will return the time in seconds since January 1, 1970. In our example, we return the number of seconds to a variable $timestampInSeconds.

$timestampInSeconds = $_SERVER['REQUEST_TIME'];

The next step once you get the the seconds is to convert it into a format that MySql will understand. In particular, MySql DateTime is ‘2008-08-01 20:01:05′. Pay attention to the leading zeros in front of the month, day, hours, minutes, and seconds. Also note that the hour field is a twenty four hour field. To accomplish this string format in PHP, we can utilize the date function. The below example will store in $mySqlDateTimea date format MySql will understand.

$mySqlDateTime= date("Y-m-d H:i:s", $timestampInSeconds);

You now have a datetime variable stored in $mySqlDateTime that can be used in a sql statement for MySql.

Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

6 Responses to “Convert DateTime From PHP to MySql Format”

  1. Good stuff,
    Thanks…as I’m developing a do it yourself visitor tracking script.

  2. John says:

    Nice to the point article. That’s just what I was looking for! Thanks.

  3. Aqeel says:

    THanx dude.
    Its really help full for me
    THanx

  4. shajakhan says:

    how can i take the time from a date time field using php,mysql

  5. Mr PHP says:

    Just wrote an article about that topic, i’m using array in order to break the DATETIME to something more readable:

    http://www.peeaitchpee.com/php/using-php-to-reformat-a-datetime-value-from-mysql/

  6. MB says:

    Succintly put

Leave a Reply