简体   繁体   English

如何在 PHP 中将 MySQL TIMESTAMP 转换为日期时间

[英]How to convert MySQL TIMESTAMP to date time in PHP

I have a MySQL DB table with a column named "timestamp" , a type of timestamp , and attribute of on update CURRENT_TIMESTAMP and a default of CURRENT_TIMESTAMP .我有一个名为列MySQL数据库表"timestamp" ,一个类型的timestamp ,以及属性on update CURRENT_TIMESTAMP和默认CURRENT_TIMESTAMP

If I add a record to the table, specifying other values, but not the timestamp, then the timestamp is automatically added like 2016-12-28 17:02:26 .如果我向表中添加一条记录,指定其他值,但不指定时间戳,则时间戳会自动添加,如2016-12-28 17:02:26

In PHP I query the table using the following query在 PHP 中,我使用以下查询查询表

SELECT * FROM history WHERE user_id = 9 ORDER BY timestamp ASC

The result of the query is saved into $rows and I use a foreach to create an array with some of the other values formatted.查询的结果保存到$rows ,我使用foreach创建一个数组,其中包含一些其他格式化的值。 I am attempting to format the time stamp to UK type 24-hour date time: dd/mm/yy, HH:MM:SS .我试图将时间戳格式化为英国类型的 24 小时日期时间: dd/mm/yy, HH:MM:SS

I have tried both the date() and strftime() functions as follows:我已经尝试了date()strftime()函数,如下所示:

$formatted_datetime = strftime("%d %m %y  %H %M %S", $row["timestamp"]); 
$formatted_datetime = date("d/m/y, H:i:s", $row["timestamp"]);

Both of these result in the following notice and the date time being output incorrectly like 01 01 70 00 33 36 :这两者都会导致以下通知和日期时间被错误地输出,如01 01 70 00 33 36

Notice: A non well formed numeric value encountered in /home/ubuntu/workspace/pset7/public/history.php on line 20注意:在第 20 行的 /home/ubuntu/workspace/pset7/public/history.php 中遇到格式不正确的数值

I am new to PHP and MySQL and so far none of the other questions or documentation I have seen have successfully addressed performing this conversion.I do not understand why strftime() does not work, nor how to do this properly?我是 PHP 和 MySQL 的新手,到目前为止,我看到的其他问题或文档都没有成功解决执行此转换的问题。我不明白为什么strftime()不起作用,也不明白如何正确执行此操作?

To do this the OO (and most flexible) way use DateTime class and use the static createFromFormat method to instantiate a new DateTime object:为此,OO(也是最灵活的)方式使用DateTime类并使用静态createFromFormat方法来实例化一个新的DateTime对象:

$new_datetime = DateTime::createFromFormat ( "Y-m-d H:i:s", $row["timestamp"] );

Now you can use the $new_datetime object to generate any string representation you'd like by calling the object's format method:现在,您可以使用$new_datetime对象通过调用该对象的format方法来生成您想要的任何字符串表示format

echo $new_datetime->format('d/m/y, H:i:s');

To boot, you since you've a DateTime object you can now also to any manner of transformation (like shifting timezones or adding days), comparison (greater or less than another DateTime ), and various time calculations (how many days/months/etc... between this and another DateTime ).要启动,因为您有一个DateTime对象,您现在还可以进行任何方式的转换(例如移动时区或添加天数)、比较(大于或小于另一个DateTime )和各种时间计算(多少天/月/等等......在这个和另一个DateTime之间)。

DateTime: http://php.net/manual/en/class.datetime.php Learn it.日期时间: http : //php.net/manual/en/class.datetime.php学习一下。 Love it.爱它。 Live it.活下去。

Normally in MySQL date timestamp save time as YYYY-MM-DD HH:MM:SS (2016-12-20 18:36:14) formate you can easily convert them as your wish using date formate but have to convert your input to time first.通常在 MySQL 日期时间戳中,将时间保存为YYYY-MM-DD HH:MM:SS (2016-12-20 18:36:14)您可以根据需要使用日期YYYY-MM-DD HH:MM:SS (2016-12-20 18:36:14)轻松转换它们,但必须将输入转换为时间第一的。 Following will do the trick以下将解决问题

$formatted_datetime = date("d/m/y, H:i:s", strtotime($row["timestamp"]));

Why not make MySQL do the work?为什么不让 MySQL 来完成这项工作呢? And do you really want mm/dd/yy, not dd/mm/yy?你真的想要 mm/dd/yy,而不是 dd/mm/yy 吗?

SELECT *, DATE_FORMAT(timestamp, '%m/%d/%y, %T') formatted_date FROM ....

Then you can extract the formatted date as $row['formatted_date'].然后您可以将格式化日期提取为 $row['formatted_date']。

See https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-formathttps://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

The date is of timestamp type which has the following format: 'YYYY-MM-DD HH:MM:SS' or '2008-10-05 21:34:02.'日期为timestamp类型,格式如下:“YYYY-MM-DD HH:MM:SS”或“2008-10-05 21:34:02”。

$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
   echo $row['date'] . "
";
}

The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function. PHP strtotime 函数将 MySQL 时间戳解析为 Unix 时间戳,可用于在 PHP 日期函数中进一步解析或格式化。

Here are some other sample date output formats that may be of practical use:以下是一些可能有实际用途的其他示例日期输出格式:

echo date("F j, Y g:i a", strtotime($row["date"]));                  // October 5, 2008 9:34 pm
echo date("m.d.y", strtotime($row["date"]));                         // 10.05.08
echo date("j, n, Y", strtotime($row["date"]));                       // 5, 10, 2008
echo date("Ymd", strtotime($row["date"]));                           // 20081005
echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"]));   // It is the 5th day.
echo date("D M j G:i:s T Y", strtotime($row["date"]));               // Sun Oct 5 21:34:02 PST 2008

I would use the Carbon class and its String Formatting我会使用Carbon 类及其字符串格式

$carbon = Carbon::instance('2016-12-28 17:02:26');

Then you can format it the way you want.然后你可以按照你想要的方式格式化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM