简体   繁体   English

Php 日期时间转换为 ISO 8601

[英]Php datetime convert to ISO 8601

I have an app that would call an Amazon api, the datetime requirements should be an ISO 8601 format.我有一个应用程序会调用 Amazon api,日期时间要求应该是 ISO 8601 格式。 I tried the Carbon like我试过碳喜欢

   'data_startTime' => 'nullable|date_format:Y-m-d H:i:s',

   Carbon::parse($request->data_startTime)->toIso8601String()

The example data_startTime示例 data_startTime

  2019-12-10 20:11:24

Which resulted to这导致

   2019-12-10T20:11:24+00:00

But per Amazon's requirement, it will just reject that param and will throw error What Amazon required is the format should like this但根据亚马逊的要求,它只会拒绝该参数并抛出错误亚马逊需要的格式应该是这样的

    2019-12-10T20:11:24.000Z

How to achieve that using Carbon or any Php DateTime class?如何使用 Carbon 或任何 Php DateTime class 来实现这一点?

One solution is to use the DateTime class, select the time zone "Z" and generate the desired format with the method of the same name.一种解决方案是使用DateTime class, select 时区“Z”并使用同名方法生成所需的格式。

$start = '2019-12-10 20:11:24';

$strDate = date_create($start,new DateTimeZone('Z'))->format('Y-m-d\TH:i:s.ve');

echo $strDate;  //2019-12-10T20:11:24.000Z

If microsecond-precision is OK, toJSON might be the cleanest option:如果微秒精度没问题, toJSON可能是最干净的选项:

echo Carbon::parse('2019-12-10 20:11:24')->toJSON();

Note that if you already JSON encode the body you send, it will just be handled automatically:请注意,如果您已经对您发送的正文进行了 JSON 编码,它将被自动处理:

echo json_encode([
  'date' => Carbon::parse('2019-12-10 20:11:24')
]);

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

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