我有一个类型为“timestamp”的数据库行。每次添加新记录时,它都会自动填充该记录的插入时间。现在,对于其中一条记录,它的值是:
2010-06-19 18:40:51
我试图通过以下方式将其转换为对用户更友好的格式:
$timeStamp = $row['date'];
$timeStamp = date( "m/d/Y", $timeStamp);
但它返回这个:
12/31/1969
我在某处读到日期函数只能用于 unix 时间戳,也许我数据库中的时间戳不是正确的时间戳,我需要先将其转换为时间戳,然后再对其使用日期函数(?) .解决方案是什么?
最佳答案
使用strtotime功能:
$timeStamp = $row['date'];
$timeStamp = date( "m/d/Y", strtotime($timeStamp));
对于示例中的日期 2010-06-19 18:40:51
,它将返回:
06/19/2010
timestamp
字段会自动更新,但您可以通过将其更改为 DEFAULT CURRENT_TIMESTAMP
来禁用该行为,否则它将自动更新。来自manual :
In a CREATE TABLE statement, the first TIMESTAMP column can be declared in any of the following ways:
With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses, the column has the current timestamp for its default value, and is automatically updated.
With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
With a DEFAULT CURRENT_TIMESTAMP clause and no ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated.
关于php - 如何从 PHP 中的时间戳格式化日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3080921/