简体   繁体   English

如何从 PHP 中的毫秒格式创建 ISO 8601 日期?

[英]How do I create from format an ISO 8601 date with milliseconds in PHP?

I am trying to parse the date 2018-07-17T17:34:08.167 into a DateTimeImmutable object in my code, which I tried to do with:我正在尝试在我的代码中将日期2018-07-17T17:34:08.167解析为DateTimeImmutable object,我尝试这样做:

\DateTimeImmutable::createFromFormat('c', $s);

However, because of the milliseconds present and the lack of the time zone, PHP returns false for this.但是,由于存在毫秒数且缺少时区,PHP 为此返回false

I then tried to create it by defining the format myself, but the problem is that T is used as a timezone abbreviation.然后我尝试通过自己定义格式来创建它,但问题是T被用作时区缩写。

\DateTimeImmutable::createFromFormat('YYYY-mm-ddTHH:ii:ss.v', $s);
\DateTimeImmutable::createFromFormat('YYYY-mm-dd\\THH:ii:ss.v', $s);

I read this answer and tried wildcards, but no dice.我读了这个答案并尝试了通配符,但没有骰子。

\DateTimeImmutable::createFromFormat('YYYY-mm-dd*HH:ii:ss.v', $s);

Anyone know how I can get this to parse?任何人都知道我怎样才能得到这个来解析?

EDIT: That moment when you spend a whole week coding in C# and then forget how to format in PHP...编辑:当你花了整整一周的时间在 C# 中编码然后忘记如何在 PHP 中格式化的那一刻......

You don't have to use 4 times Y ( YYYY ), because Y represent year in 4 digits.您不必使用 4 次Y ( YYYY ),因为Y以 4 位数字表示年份。 Same for other "time-markers".其他“时间标记”也一样。

$s='2018-07-17T17:34:08.167';
var_dump(\DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s.v', $s));

Output: Output:

object(DateTimeImmutable)#1 (3) {
  ["date"]=>
  string(26) "2018-07-17 17:34:08.167000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "Europe/Paris"
}

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

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