Convert from MySQL datetime to another format with PHP

后端 未结 18 1195
醉话见心
醉话见心 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:27

    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.

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

    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.

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

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

    $date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
    $date->setTimezone(new \DateTimeZone('Europe/Berlin')); // optional
    echo $date->format('m/d/y h:i a');
    
    0 讨论(0)
  • 2020-11-22 01:33

    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)))
    
    0 讨论(0)
  • 2020-11-22 01:35

    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));
    }
    
    0 讨论(0)
  • 2020-11-22 01:40

    Use the date function:

    <?php
        echo date("m/d/y g:i (A)", $DB_Date_Field);
    ?>
    
    0 讨论(0)
提交回复
热议问题