在 PHP 中从 SQL 格式化时间戳的最简单方法是什么?

2022-01-12 00:00:00 timestamp formatting php mysql

完成下面的 PHP 代码以使输出采用用户友好格式(例如,2006 年 10 月 27 日")的最简单、最快的方法是什么?

What is the simplest, fastest way to complete the PHP code below such that the output is in a user-friendly format (for example, "October 27, 2006")?

$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = ???($row['my_timestamp']);
echo $formatted_date;

推荐答案

你可以使用 MySQL 为你做这件事,

You could use MySQL to do this for you,

$result = mysql_query("SELECT DATE_FORMAT(my_timestamp, '%M %d, %Y) AS my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = $row['my_timestamp'];
echo $formatted_date;

或者使用PHP,

$result = mysql_query("SELECT my_timestamp FROM some_table WHERE id=42", $DB_CONN);
$row = mysql_fetch_array($result);
$formatted_date = strftime('%B %d, %y', $row['my_timestamp']);
echo $formatted_date;

相关文章