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?
$valid_date = date( 'm/d/y g:i A', strtotime($date));
Reference: http://php.net/manual/en/function.date.php
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
The approach I suggest works like the following. First, you create a basic datetime object from a mysql-formatted string; and then you format it the way you like. Luckily, mysql datetime is ISO8601-compliant, so the code itself could look quite simple and elegant. Keep in mind though that datetime
column doesn't have a timezone information, so you need to convert it appropriately.
Here's the code:
(new ISO8601Formatted(
new FromISO8601('2038-01-19 11:14:07'),
'm/d/Y h:iA'
))
->value();
It outputs 01/19/2038 11:14AM
-- hopefully what you expect.
This example uses meringue library. You can check out some more of it if you fancy.
If you are using PHP 5, you can also try
$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");
$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";
Forget all. Just use:
$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))