Convert from MySQL datetime to another format with PHP

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

    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)

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

    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.

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

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

    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.

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

    This should format a field in an SQL query:

    SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
    
    0 讨论(0)
  • 2020-11-22 01:27

    This will work...

    echo date('m/d/y H:i (A)',strtotime($data_from_mysql));
    
    0 讨论(0)
提交回复
热议问题