Convert from MySQL datetime to another format with PHP

后端 未结 18 1215
醉话见心
醉话见心 2020-11-22 01:08

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?

相关标签:
18条回答
  • 2020-11-22 01:13
    $valid_date = date( 'm/d/y g:i A', strtotime($date));
    

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

    0 讨论(0)
  • 2020-11-22 01:15

    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

    0 讨论(0)
  • 2020-11-22 01:16

    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.

    0 讨论(0)
  • 2020-11-22 01:17

    If you are using PHP 5, you can also try

    $oDate = new DateTime($row->createdate);
    $sDate = $oDate->format("Y-m-d H:i:s");
    
    0 讨论(0)
  • 2020-11-22 01:18
    $date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";
    
    0 讨论(0)
  • 2020-11-22 01:19

    Forget all. Just use:

    $date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))
    
    0 讨论(0)
提交回复
热议问题