php - 如何从 PHP 中的时间戳格式化日期?

标签 php mysql

我有一个类型为“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/

相关文章:

php - 在codeigniter中将变量从View页面传输到Controller页面是否理想?

javascript - PHP MySQL : count views per month for jQuery charts

php - 粘贴到 Skype 或其他社交媒体时如何在文本中显示公共(public)图像

mysql - 用序列号mysql更新列

php - 在上传时将图像转换为所有尺寸与通过 php 请求调整大小

php - 如何更改动态生成的内容 Javascript 和 PHP 的可见性

php 删除该字符之前的所有内容

php - 使用 php 显示 mysql 数据库中从开始日期到结束日期的数据,其中用户提供开始和结束日期

mysql - 计算 Sum() 但不包括 JOIN

Mysql 使用 join 统计案例