如何在 PHP 中将日期时间转换为 ISO 8601
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5322285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert datetime to ISO 8601 in PHP
提问by wow
How do I convert my time from 2010-12-30 23:21:46
to ISO 8601 date format? (-_-;)
如何将我的时间从2010-12-30 23:21:46
ISO 8601 日期格式转换为日期格式?(-_-;)
回答by alex
Object Oriented
面向对象
This is the recommended way.
这是推荐的方式。
$datetime = new DateTime('2010-12-30 23:21:46');
echo $datetime->format(DateTime::ATOM); // Updated ISO8601
Procedural
程序
For older versions of PHP, or if you are more comfortable with procedural code.
对于旧版本的 PHP,或者如果您更习惯于程序代码。
echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));
回答by trante
After PHP 5 you can use this: echo date("c");
form ISO 8601 formatted datetime.
在 PHP 5 之后你可以使用这个:echo date("c");
form ISO 8601 formatted datetime。
Note for comments:
评论注意:
Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh]
.
关于这一点,这两个表达式都对时区有效,对于基本格式:±[hh]:[mm], ±[hh][mm], or ±[hh]
.
But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c")
. A similar discussion here.
但请注意,+0X:00 是正确的,而 +0X00 对于扩展使用是不正确的。所以最好使用date("c")
. 类似的讨论在这里。
回答by John Slegers
How to convert from ISO 8601 to unixtimestamp :
如何从 ISO 8601 转换为 unixtimestamp :
strtotime('2012-01-18T11:45:00+01:00');
// Output : 1326883500
How to convert from unixtimestamp to ISO 8601 (timezone server) :
如何从 unixtimestamp 转换为 ISO 8601(时区服务器):
date_format(date_timestamp_set(new DateTime(), 1326883500), 'c');
// Output : 2012-01-18T11:45:00+01:00
How to convert from unixtimestamp to ISO 8601 (GMT) :
如何从 unixtimestamp 转换为 ISO 8601 (GMT):
date_format(date_create('@'. 1326883500), 'c') . "\n";
// Output : 2012-01-18T10:45:00+00:00
How to convert from unixtimestamp to ISO 8601 (custom timezone) :
如何从 unixtimestamp 转换为 ISO 8601(自定义时区):
date_format(date_timestamp_set(new DateTime(), 1326883500)->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2012-01-18T05:45:00-05:00
回答by Brighton Madire
date("c");
//output : 2018-02-28T13:12:44+01:00
回答by Rúbia Alves
If you try set a value in datetime-local
如果您尝试在 datetime-local 中设置一个值
date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));
//output : 2010-12-30T23:21