481

I have a datetime column in MySQL.

How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?

3
  • 4
    What we need to know is how the date is stored within the SQL. Is it Timestamp or Datetime or unixtime? Commented Sep 25, 2008 at 23:15
  • They are stored not in unix time, just like a normal date, PHP is the one that deal with it as seconds and stuff. I would recommend you to use the PHP OOP datetime functions, they are very easy to use.
    – Gucho Ca
    Commented Jan 15, 2014 at 11:25
  • 3
    Can I recommend and alternative to your date format? mm/dd/yy is very American, and those of us living in other parts of the world get more than a little irritable on trying to second-guess what is meant by 11-12-13. The more universal standard is yyyy-mm-dd, and is part of the ISO 8601 standard. Failing that, you should use the month name, not the number.
    – Manngo
    Commented Apr 23, 2017 at 5:15

18 Answers 18

570

If you're looking for a way to normalize a date into MySQL format, use the following

$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );

The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.

The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format.

(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)

10
  • 28
    this answer is confusing the topic
    – Alex K
    Commented Jun 6, 2013 at 9:07
  • 7
    @0xBAADF00D: please read the question again...nobody asked about the MySQL standard format.
    – user7116
    Commented Aug 22, 2013 at 15:11
  • 3
    of course, but, when standard exist, it could be nice to follow standard (it avoid headache later when another dev work on your code) xD
    – Thibault
    Commented Aug 22, 2013 at 17:27
  • 5
    The question asks to output in the format mm/dd/yy H:M (AM/PM), not "Y-m-d H:i:s".
    – Rikki
    Commented Jan 10, 2014 at 17:01
  • 7
    does not work for who? Accepted answer will work if you want to convert from MySQL into mm/dd/yy H:M (AM/PM) as OP requested. Just because you want to do the opposite does not make accepted answer wrong.
    – toxalot
    Commented Mar 13, 2014 at 2:22
324

To convert a date retrieved from MySQL into the format requested (mm/dd/yy H:M (AM/PM)):

// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM

Refer to the PHP date formatting options to adjust the format.

7
  • Where is this $row object supposed to be from?
    – Mike
    Commented Mar 1, 2013 at 21:02
  • 27
    I could be wrong, but I think some of you are missing the point. He wants the output to be in "m/d/y g:i A" format, pulling the original date from a DATETIME field. So his code works. @Mike $row->createdate is just Tim's datetime column. Commented Mar 13, 2013 at 14:48
  • 4
    @AsTeR answer is only confusing if you misread the question. OP answered own question and wants to take a date from MySQL and output to requested format: mm/dd/yy H:M (AM/PM).
    – toxalot
    Commented Mar 13, 2014 at 1:45
  • @TimBoland I think answer could be improved if from was emphasized as well as the requested format mm/dd/yy H:M (AM/PM). And it could benefit from a link to the date function. I tried to suggest an edit, but it was rejected.
    – toxalot
    Commented Mar 13, 2014 at 1:49
  • 1
    Fun fact: this answer is roughly equivalent to the one just below (which has virtually no downvotes), but it got >40 downvotes because it answers the OP's question, which differs from that which people who come to this page actually have.
    – Clément
    Commented Apr 29, 2014 at 22:53
117

If you are using PHP 5, you can also try

$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");
1
  • As stated above in comments, the standard format is ("Y-m-d H:i:s")
    – Yannickv
    Commented Nov 13, 2014 at 10:31
48
$valid_date = date( 'm/d/y g:i A', strtotime($date));

Reference: http://php.net/manual/en/function.date.php

4
  • I think people downvote because they are confused about OP question. Most read the question to be the opposite of what it actually is. The other possibility is that this is very similar to accepted answer that was posted 5+ years ago.
    – toxalot
    Commented Mar 13, 2014 at 1:19
  • 1
    The link you reference does not point to the function you are using, nor does it explain the format. I think php.net/function.date.php would be better.
    – toxalot
    Commented Mar 13, 2014 at 2:04
  • @toxalot The accepted answer is wrong. It edited after my answer & about my link i replace your link. Thanks
    – Tony Stark
    Commented Apr 1, 2014 at 6:38
  • 1
    This whole Q&A has a sordid history. The accepted answer was wrong between April 29, 2013 and May 24, 2013. It was correct when you first posted your answer. Your answer was wrong until May 29, 2013, after which it became very similar to accepted answer.
    – toxalot
    Commented Apr 1, 2014 at 17:08
34

Finally the right solution for PHP 5.3 and above: (added optional Timezone to the Example like mentioned in the comments)

without time zone:

$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date);
echo $date->format('m/d/y h:i a');

with time zone:

$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone('Europe/Berlin'));
echo $date->format('m/d/y h:i a');
4
  • its error.. Class 'App\Controller\DateTime' not found ..using php 6.4
    – aswzen
    Commented Nov 26, 2017 at 11:49
  • 1
    If you are working in another namespace, you have to call it with a backslash in front of it: \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date); Commented Dec 4, 2017 at 22:30
  • 3
    Don't forget to specify the timezone when you create your date object! Otherwise, your formatted date might be several hours off. Your datetime columns should be UTF8, so pass new DateTimeZone('UTC') as the 3rd parameter to ensure PHP knows. Commented May 14, 2019 at 19:16
  • This is the correct answer that outputs the OP's desired format, just take care of timezones Commented Aug 26, 2019 at 20:55
10

An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.

If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.

1
  • 13
    -1 because formatting date in DB is not good idea. Multilanguage web need different date formats and then you have to format date in PHP (business logic language in common). When you wrote about date function, then you should wrote about strottime function also to help someone instead of "but you'll have to convert your database value into a timestamp first". Commented Apr 15, 2013 at 22:23
10

Forget all. Just use:

$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))
0
9

To correctly format a DateTime object in PHP for storing in MySQL use the standardised format that MySQL uses, which is ISO 8601.

PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.

$dtNow = new DateTime();
$mysqlDateTime = $dtNow->format(DateTime::ISO8601);

This, and a list of other PHP DateTime constants are available at http://php.net/manual/en/class.datetime.php#datetime.constants.types

2
  • MySQL doesn't actually use this format, and MySQL generates a warning if you include the "+xxxx" time zone designator that gets generated by it. UPDATE X SET Y = '2014-03-31T15:00:00+0100' where Z; Query OK, 0 rows affected, 1 warning (0.06 sec) Rows matched: 1 Changed: 0 Warnings: 1 Commented Jan 13, 2014 at 17:11
  • OP wants to take a date from MySQL format and convert to mm/dd/yy H:M (AM/PM).
    – toxalot
    Commented Mar 13, 2014 at 2:13
9

This should format a field in an SQL query:

SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
1
  • You should specify MySQL query, not just SQL, because that won't necessarily work with all databases. While OP asked for PHP solution, this is a good alternative that OP may not have known about. However, this will not provide the requested format. To get the format OP requested, you'd need '%m/%d/%y %h:%i %p'.
    – toxalot
    Commented Mar 13, 2014 at 2:48
7

Use the date function:

<?php
    echo date("m/d/y g:i (A)", $DB_Date_Field);
?>
1
  • 26
    Doesn't the date() function expect an integer timestamp rather than a datetime specified in the question?
    – Loftx
    Commented Apr 6, 2010 at 10:55
5

Depending on your MySQL datetime configuration. Typically: 2011-12-31 07:55:13 format. This very simple function should do the magic:

function datetime()
{
    return date( 'Y-m-d H:i:s', time());
}

echo datetime(); // display example: 2011-12-31 07:55:13

Or a bit more advance to match the question.

function datetime($date_string = false)
{
    if (!$date_string)
    {
        $date_string = time();
    }
    return date("Y-m-d H:i:s", strtotime($date_string));
}
1
  • 1
    This does not answer OP question. OP wants to take a date from MySQL format and convert to mm/dd/yy H:M (AM/PM). Plus this will just format current time, not a specific date.
    – toxalot
    Commented Mar 13, 2014 at 0:46
5
SELECT 
 DATE_FORMAT(demo.dateFrom, '%e.%M.%Y') as dateFrom,
 DATE_FORMAT(demo.dateUntil, '%e.%M.%Y') as dateUntil
FROM demo

If you dont want to change every function in your PHP code, to show the expected date format, change it at the source - your database.

It is important to name the rows with the as operator as in the example above (as dateFrom, as dateUntil). The names you write there are the names, the rows will be called in your result.

The output of this example will be

[Day of the month, numeric (0..31)].[Month name (January..December)].[Year, numeric, four digits]

Example: 5.August.2015

Change the dots with the separator of choice and check the DATE_FORMAT(date,format) function for more date formats.

4

You can also have your query return the time as a Unix timestamp. That would get rid of the need to call strtotime() and make things a bit less intensive on the PHP side...

select  UNIX_TIMESTAMP(timsstamp) as unixtime from the_table where id = 1234;

Then in PHP just use the date() function to format it whichever way you'd like.

<?php
  echo date('l jS \of F Y h:i:s A', $row->unixtime);
?>

or

<?php
  echo date('F j, Y, g:i a', $row->unixtime);
?>

I like this approach as opposed to using MySQL's DATE_FORMAT function, because it allows you to reuse the same query to grab the data and allows you to alter the formatting in PHP.

It's annoying to have two different queries just to change the way the date looks in the UI.

1
  • I like the idea of using UNIX_TIMESTAMP to eliminate the need for strtotime. This answer would be better if it gave an example of formatting the time in the format OP actually requested.
    – toxalot
    Commented Mar 13, 2014 at 2:57
1

You can have trouble with dates not returned in Unix Timestamp, so this works for me...

return date("F j, Y g:i a", strtotime(substr($datestring, 0, 15)))
1
  • 1
    This does not convert the date to format requested by OP.
    – toxalot
    Commented Mar 13, 2014 at 2:29
1

This will work...

echo date('m/d/y H:i (A)',strtotime($data_from_mysql));
1
  • 1
    That format mixes 24 time with AM/PM. Otherwise, it is the same as accepted answer that was posted 5+ years ago.
    – toxalot
    Commented Mar 13, 2014 at 2:09
1

Direct output e.g. in German format:

  echo(date('d.m.Y H:i:s', strtotime($row["date_added"])));
0

Using PHP version 4.4.9 & MySQL 5.0, this worked for me:

$oDate = strtotime($row['PubDate']);
$sDate = date("m/d/y",$oDate);
echo $sDate

PubDate is the column in MySQL.

1
  • 1
    This does not convert the date to format requested by OP
    – toxalot
    Commented Mar 13, 2014 at 2:50
-1
$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";
1
  • 1
    This does not answer OP question. OP wants to take a date from MySQL format and convert to mm/dd/yy H:M (AM/PM). This does the opposite. Plus it takes input from a form rather than the database.
    – toxalot
    Commented Mar 13, 2014 at 1:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.