faqts : Computers : Programming : Languages : PHP : Database Backed Sites : General

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

105 of 108 people (97%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How to display 'June 19, 2021' from the value '2021-06-19' got from a MySQL database using PHP3?

Jul 26th, 2001 07:08
Paul R, Jon Bertsch, Philip Olson, Frank Quist, Ben Udall, Dee Lee, Pruet Boonma, Richard Heyes, Sheni R. Meledath, Onno Benschop,


Allowing SQL to do this directly is by far the most efficient method,
such as the following, which will format the date according to the
manual specifications :
  http://www.mysql.com/doc/D/a/Date_and_time_functions.html
Check the the syntax for the Mysql date_format function 
in the Mysql Documentation single quotes delimit the '%M %d, %Y'
  SELECT date_format(somedatefield,'%M %d, %Y')
  FROM   tablename;
Check the the syntax for the Mysql date_format function
An Additional SQL statement type can also be used. If you have a number
of fields and want to output them this is an alternate style.
Say I have a DB table with pub_date, title and link fields. I can use
the following select statement:
"SELECT pub_date, title, link, date_format(pub_date, '%M %e, %Y') as
pub_date from my_table";
If you store your dates in MySQL as yyyy-mm-dd the output from the SQL
formatting in this case will be (using 2021-06-19)
June 19, 2000.
Using Mysql you can also use a query like this:
  SELECT unix_timestamp(somedatefield)
  FROM tablename;
If you do this, Mysql will return the date as a unix timestamp. You can
then use date() to create proper formatting of the timestamp.  Now, PHP
can also do such things, here are a couple ways :
First, using strtotime() may work as it'll interpet this date format,
for example :
  <?php
    $input = '2021-06-19';
    print date('F d, Y',strtotime($input));  // prints June 19, 2021
  ?>
  http://www.php.net/manual/function.strtotime.php
It works for standard date formats.  Secondly, you can create your own
function to deal with the given situation, such as :
  <?php
    $input = '2021-06-19';
    print convertDate($input); // prints June 19, 2021
      function convertDate($input,$format='F d, Y')
      {
        $d = explode('-', $input);
        return date($format, mktime(0, 0, 0, $d[1], $d[2], $d[0]));
      }
  ?>
Essentially, allow your database to do it if you can.  Otherwise, PHP
can do it.  Be sure to check out date() within manual :
  http://www.php.net/manual/function.date.php