我想使用时间戳。
我知道这会输出一个时间戳:
$date = date_create();
echo date_format($date, 'U');
但我想知道如何利用那个时间戳。--> 将其保存到数据库,稍后将其转换为所需的时区,然后以我选择的格式输出。
我只是不知道该怎么做。
如何使用时间戳?
由于您的意图只是存储然后显示您的时间戳,您可以让 mysql 完成这项工作。
您的表 DDL 可能看起来像
CREATE TABLE `posts` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`post_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`post` varchar(512) DEFAULT NULL,
PRIMARY KEY (`id`)
);
重要部分DEFAULT
CURRENT_TIMESTAMP
这样当前时间戳将分配给 post_date 列INSERT
INSERT INTO `posts` (`post`) VALUES ('post1');
然后您可以使用DATE_FORMAT
从 mysql 获取格式化的时间戳数据
SELECT id, DATE_FORMAT(post_date, '%m/%d/%Y %H:%i:%s') post_date, post
FROM `posts`
输出
+----+---------------------+-------+
| id | post_date | post |
+----+---------------------+-------+
| 1 | 02/20/2013 23:45:43 | post1 |
| 2 | 02/20/2013 23:45:43 | post2 |
+----+---------------------+-------+
但是如果你想用 php 格式化它,你可以UNIX_TIMESTAMP()
先在查询中使用
SELECT id, UNIX_TIMESTAMP(post_date) post_date, post FROM `posts`
然后date()
像这样格式化它,假设你$row
通过你最喜欢的扩展(PDO或mysqli)获取了一行
date_default_timezone_set('America/New_York');
echo date('m/d/Y H:i:s',$row['post_date']);
输出
02/20/2013 23:45:43