简体   繁体   English

PHP - 格式化日期 ISO8601?

[英]PHP - format date ISO8601?

I have a year (2002) and I'm trying to get it into the following format:我有一年(2002 年),我正在尝试将其转换为以下格式:

2002-00-00T00:00:00 2002-00-00T00:00:00

I tried various iterations, the last of which was this:我尝试了各种迭代,最后一次是这样的:

$testdate = DateTime::createFromFormat(DateTime::ISO8601, date("c"))
echo date_format($testdate, '2002'); 

But, even if I come close, it always seems to add +00:00 to the end of it...但是,即使我接近,它似乎总是在末尾添加 +00:00 ......

The 'c' format in PHP always appends the timezone offset. PHP 中的“c”格式总是附加时区偏移量。 You can't avoid that.你无法避免这种情况。 But you can build the date yourself from components:但是您可以自己从组件构建日期:

date('Y-m-d\TH:i:s', $testdate);

Best way is to use constants (PHP 5 >= 5.5.0, PHP 7)最好的方法是使用常量(PHP 5 >= 5.5.0,PHP 7)

date(DATE_ISO8601, $timeToChange);

Docs: http://php.net/manual/en/class.datetimeinterface.php#datetime.constants.types文档: http : //php.net/manual/en/class.datetimeinterface.php#datetime.constants.types

date('Y-m-d\TH:i:s\Z', time() - date('Z'));

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals.问题多次出现在4 或 8次决赛中的毫秒和最终微秒。 To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:要将DATE转换为 ISO 8601 “date(DATE_ISO8601)”,这些是对我有用的解决方案之一:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

Previous published: https://stackoverflow.com/a/61796705/5898408上一篇: https : //stackoverflow.com/a/61796705/5898408

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

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