Thursday 1 August 2019

How to convert MySQL timestamp to PHP date type

Let’s say you have the following PHP code that extracts the date from the times table in your MySQL database. The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’
  1. $res = mysql_query("SELECT date FROM times;");
  2. while ( $row = mysql_fetch_array($res) ) {
  3.    echo $row['date'] . "<br />";
  4. }

This date format that is in the output is in the timestamp format, 2008-10-05 21:34:02, which is not surprising, but you want something that is more “user-friendly” or “readable” as in “9:34 pm October 5, 2008.”
Let’s go back to the drawing board and try again:
  1. $res = mysql_query("SELECT date FROM times;");
  2. while ( $row = mysql_fetch_array($res) ) {
  3.    echo date("g:i a F j, Y ", strtotime($row["date"])) . "<br />";
  4. }
A sample output from this PHP code would be 9:34 pm October 5, 2008which is much more user-friendly.
The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function.
Here are some other sample date output formats that may be of practical use:
  1. echo date("F j, Y g:i a", strtotime($row["date"]));                  // October 5, 2008 9:34 pm
  2. echo date("m.d.y", strtotime($row["date"]));                         // 10.05.08
  3. echo date("j, n, Y", strtotime($row["date"]));                       // 5, 10, 2008
  4. echo date("Ymd", strtotime($row["date"]));                           // 20081005
  5. echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"]));   // It is the 5th day.
  6. echo date("D M j G:i:s T Y", strtotime($row["date"]));               // Sun Oct 5 21:34:02 PST 2008

0 comments:

Post a Comment