如何显示的日期为ISO 8601格式,PHP
-
05-09-2019 - |
题
我想显示从我的MySQL数据库中的日期时间与PHP的ISO 8601格式化字符串,但它的到来了错误的。
2008 10月17日被出来为:1969-12-31T18:33:28-06:00,这显然是不正确(年应2008不1969)
这是我使用的代码:
<?= date("c", $post[3]) ?>
从我的MySQL数据库$post[3] is the datetime (CURRENT_TIMESTAMP)
。
任何想法是怎么回事?
解决方案
的第二个参数 date
是一个UNIX时间戳,而不是一个数据库的时间戳字符串。
您需要将您的数据库时间戳转换与的strtotime 。
<?= date("c", strtotime($post[3])) ?>
其他提示
使用 DateTime类使用在PHP 5.2版本,将这样进行:
$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');
作为PHP 5.4的可以做到这一点作为一个班轮:
echo (new DateTime('17 Oct 2008'))->format('c');
程序样式:
echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
面向对象的样式:
$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00
混合1:
echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
混合2:
echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00
注意:
1)也可以使用'Y-m-d\TH:i:sP'
作为替代'c'
为您的格式。
2)的输入的默认时区是服务器的时区。如果你想输入的是一个不同的时区,你需要明确设置时区。这也将影响您的输出,但是:
echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00
3)如果你想输出是从您输入不同的时区,你可以明确地设定时区:
echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00
有关预PHP 5:
function iso8601($time=false) {
if(!$time) $time=time();
return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';
}
下面是用于预PHP 5良好的作用: 我加入GMT差底,它不是硬编码。
function iso8601($time=false) {
if ($time === false) $time = time();
$date = date('Y-m-d\TH:i:sO', $time);
return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}
不隶属于 StackOverflow