Convert from MySQL datetime to another format with

2018-12-31 05:11发布

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?

17条回答
不流泪的眼
2楼-- · 2018-12-31 05:21

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.

查看更多
美炸的是我
3楼-- · 2018-12-31 05:24

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)

查看更多
琉璃瓶的回忆
4楼-- · 2018-12-31 05:25
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.

查看更多
像晚风撩人
5楼-- · 2018-12-31 05:26

Use the date function:

<?php
    echo date("m/d/y g:i (A)", $DB_Date_Field);
?>
查看更多
春风洒进眼中
6楼-- · 2018-12-31 05:30

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.

查看更多
十年一品温如言
7楼-- · 2018-12-31 05:32
$valid_date = date( 'm/d/y g:i A', strtotime($date));

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

查看更多
登录 后发表回答