我正在向 twitter API 发出请求,我想从 php 中的日期中提取时间并存储在 mysql 中。有人知道该怎么做吗?
我从结果中得到的时间和日期是这样的...created_at": "Thu, 26 Jul 2012 22:16:59 +0000"
谢谢
最佳答案
在数据库中存储时间戳
使用strtotime()
在 PHP 端和 FROM_UNIXTIME()
在 MySQL 方面。
简而言之,基本上您的代码可能如下所示:
$twitter_timestamp = 'Thu, 26 Jul 2012 22:16:59 +0000';
$php_time = strtotime($twitter_timestamp);
$query = 'INSERT INTO `some_table` VALUES ("' . $php_time . '");';
以上假定您将时间戳存储在具有适当类型 (TIMESTAMP
) 的列中。要详细了解 TIMESTAMP
、DATE
和 DATETIME
之间的差异,请参阅此文档页面:MySQL Documentation: The DATE, DATETIME, and TIMESTAMP Types .
将时间存储为字符串
如果您想以不识别时区的方式存储时间戳(TIMESTAMP
之外的任何内容,并且不包括时区信息),您需要在PHP 端:
$twitter_timestamp = 'Thu, 26 Jul 2012 22:16:59 +0000';
$php_time = strtotime($twitter_timestamp);
// Optionally set local timezone:
date_default_timezone_set('America/Los_Angeles');
$php_timestamp = strftime('%T', $php_time); // will give "%H:%M:%S" timestamp
$query = 'INSERT INTO `some_table` VALUES ("' . $php_timestamp . '");';
请注意,date_default_timezone_set()
call 是可选的 - 如果你想要某个特定时区的时间,而不是当前的时间。以上假定您需要“HH:MM:SS
”形式的时间戳。
关于php - 从php中的日期中提取时间并存储在mysql中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11679264/