477

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?

davejal
  • 6,009
  • 10
  • 39
  • 82
Tim Boland
  • 10,127
  • 8
  • 27
  • 25
  • 4
    What we need to know is how the date is stored within the SQL. Is it Timestamp or Datetime or unixtime? – Ólafur Waage Sep 25 '08 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 Jan 15 '14 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 Apr 23 '17 at 05:15

18 Answers18

563

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)

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
kta
  • 19,412
  • 7
  • 65
  • 47
323

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.

Vladimir Vukanac
  • 944
  • 16
  • 29
Tim Boland
  • 10,127
  • 8
  • 27
  • 25
  • Where is this `$row` object supposed to be from? – Mike Mar 01 '13 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. – Mere Development Mar 13 '13 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 Mar 13 '14 at 01: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](http://stackoverflow.com/review/suggested-edits/4325627), but it was rejected. – toxalot Mar 13 '14 at 01:49
  • @toxalot and of course, we all read the whole question three times before jumping to copy paste the answer code ;) – AsTeR Mar 13 '14 at 08:27
  • 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 Apr 29 '14 at 22:53
  • Use this to output DateTime from MySql to eg. web page in ~English format. – Vladimir Vukanac Nov 21 '14 at 10:01
116

If you are using PHP 5, you can also try

$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");
enobrev
  • 22,314
  • 7
  • 42
  • 53
48
$valid_date = date( 'm/d/y g:i A', strtotime($date));

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

George G
  • 7,443
  • 12
  • 45
  • 59
Tony Stark
  • 8,064
  • 8
  • 44
  • 63
  • 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 Mar 13 '14 at 01:19
  • 1
    The link you reference does not point to the function you are using, nor does it explain the format. I think http://php.net/function.date.php would be better. – toxalot Mar 13 '14 at 02:04
  • @toxalot The accepted answer is wrong. It edited after my answer & about my link i replace your link. Thanks – Tony Stark Apr 01 '14 at 06: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 Apr 01 '14 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');
Hasenpriester
  • 452
  • 5
  • 9
  • its error.. Class 'App\Controller\DateTime' not found ..using php 6.4 – aswzen Nov 26 '17 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);` – Hasenpriester Dec 04 '17 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. – Eric Seastrand May 14 '19 at 19:16
  • This is the correct answer that outputs the OP's desired format, just take care of timezones – Accountant م Aug 26 '19 at 20:55
11

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.

flash
  • 388
  • 4
  • 15
  • 12
    -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". – Boris Šuška Apr 15 '13 at 22:23
10

Forget all. Just use:

$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nixis
  • 510
  • 5
  • 10
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

Greg
  • 21,235
  • 17
  • 84
  • 107
  • 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 – George Lund Jan 13 '14 at 17:11
  • OP wants to take a date ***from*** MySQL format and convert *to* **mm/dd/yy H:M (AM/PM)**. – toxalot Mar 13 '14 at 02:13
9

This should format a field in an SQL query:

SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
riz
  • 115
  • 1
  • 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 Mar 13 '14 at 02:48
7

Use the date function:

<?php
    echo date("m/d/y g:i (A)", $DB_Date_Field);
?>
Gustavo Carreno
  • 9,499
  • 13
  • 45
  • 76
  • 26
    Doesn't the date() function expect an integer timestamp rather than a datetime specified in the question? – Loftx Apr 06 '10 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));
}
tfont
  • 10,891
  • 7
  • 56
  • 52
  • 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 Mar 13 '14 at 00: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.

Rangel
  • 288
  • 3
  • 3
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
phatduckk
  • 1,775
  • 1
  • 14
  • 17
  • 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 Mar 13 '14 at 02:57
1

This will work...

echo date('m/d/y H:i (A)',strtotime($data_from_mysql));
Mihir Vadalia
  • 93
  • 1
  • 3
  • 1
    That format mixes 24 time with AM/PM. Otherwise, it is the same as accepted answer that was posted 5+ years ago. – toxalot Mar 13 '14 at 02:09
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)))
Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
matt.j.crawford
  • 392
  • 2
  • 5
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Direct output e.g. in German format:

  echo(date('d.m.Y H:i:s', strtotime($row["date_added"])));
-1
$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62
  • 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 Mar 13 '14 at 01:09