简体   繁体   English

如何格式化UTC日期以在php中使用Z(祖鲁语)区域指示符?

[英]How to format an UTC date to use the Z (Zulu) zone designator in php?

I need to display and handle UTC dates in the following format:我需要按以下格式显示和处理 UTC 日期:

2013-06-28T22:15:00Z 2013-06-28T22:15:00Z

As this format is part of the ISO8601 standard I have no trouble creating DateTime objects from strings like the one above.由于此格式是 ISO8601 标准的一部分,因此我可以轻松地从上述字符串创建 DateTime 对象。 However I can't find a clean way (meaning no string manipulations like substr and replace, etc.) to present my DateTime object in the desired format.但是我找不到一种干净的方法(意味着没有像 substr 和 replace 等字符串操作)来以所需的格式显示我的 DateTime 对象。 I tried to tweak the server and php datetime settings, with little success.我试图调整服务器和 php 日期时间设置,但收效甚微。 I always get:我总是得到:

$date->format(DateTime::ISO8601); // gives 2013-06-28T22:15:00+00:00

Is there any date format or configuration setting that will give me the desired string?是否有任何日期格式或配置设置可以为我提供所需的字符串? Or I'll have to append the 'Z' manually to a custom time format?或者我必须手动将“Z”附加到自定义时间格式?

No, there is no special constant for the desired format.不,所需的格式没有特殊的常量。 I would use:我会用:

$date->format('Y-m-d\TH:i:s\Z');

But you will have to make sure that the times you are using are really UTC to avoid interpretation errors in your application.但是您必须确保您使用的时间确实是 UTC,以避免在您的应用程序中出现解释错误。

为了以所需格式获取 UTC 日期,您可以使用以下内容:

gmdate('Y-m-d\TH:i:s\Z', $date->format('U'));

If you are using Carbon then the method is:如果您使用的是 Carbon,则方法是:

echo $dt->toIso8601ZuluString();    
// 2019-02-01T03:45:27Z

To do this with the object-oriented style date object you need to first set the timezone to UTC, and then output the date:要使用面向对象样式的日期对象执行此操作,您需要首先将时区设置为 UTC,然后输出日期:

function dateTo8601Zulu(\DateTimeInterface $date):string {
  return (clone $date)
    ->setTimezone(new \DateTimeZone('UTC'))
    ->format('Y-m-d\TH:i:s\Z');
}

Edit: clone object before changing timezone.编辑:在更改时区之前克隆对象。

In PHP 8 the format character p was added:PHP 8中添加了格式字符p

$timestamp = new DateTimeImmutable('2013-06-28T22:15:00Z');
echo $timestamp->format('Y-m-d\TH:i:sp');
// 2013-06-28T22:15:00Z

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

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