如何将PHP DateTime对象转换为ISO字符串? [英] How to convert a PHP DateTime object to ISO string?

查看:79
本文介绍了如何将PHP DateTime对象转换为ISO字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以MS格式接收的JSON日期。看起来像这样:

I have a date that I receive in MS format for JSON dates. It looks like this:

/Date(1365004652303)/

我可以通过执行以下操作将其转换为PHP DateTime对象:

I can convert it to a PHP DateTime object by doing this:

$timestamp = round(((int) $originalMSdate) / 1000);
$convertedDate = new DateTime();
$convertedDate->setTimestamp($timestamp);

不过,最终,我需要将其作为ISO 8601格式的字符串。我尝试将其转换为ISO日期对象&然后使用strval()将其转换为字符串,但strval()不适用于日期对象。

Ultimately, though, I need it to be a string in ISO 8601 format. I tried then converting it to an ISO date object & then converting that to a string with strval() but strval() doesn't work on date objects.

我也尝试过

$dateString = date_format($convertedDate, 'YY-MM-DD H:i:s'); 

但我还需要它包含时区信息,例如:2015-10-01T21:22: 57.057Z
我没有在date_format中看到该字符。

but I need it to also include timezone info, like this: 2015-10-01T21:22:57.057Z I don't see characters for that in date_format.

如何实现?

编辑:我应该澄清一下,我不打印结果字符串。我需要将其传递给接受字符串数据类型的数据库中的字段。

I should clarify that I'm not printing the resulting string. I need to pass it to a field in a database that accepts a string datatype.

推荐答案

请尝试以下代码

<?php
// input
$time = microtime(true);
// Determining the microsecond fraction
$microSeconds = sprintf("%06d", ($time - floor($time)) * 1000000);
// Creating DT object
$tz = new DateTimeZone("Etc/UTC");
$dt = new DateTime(date('Y-m-d H:i:s.'. $microSeconds, $time), $tz);
$iso8601Date = sprintf(
    "%s%03d%s",
    $dt->format("Y-m-d\TH:i:s."),
    floor($dt->format("u")/1000),
    $dt->format("O")
);
// Formatting according to ISO 8601-extended
var_dump(
     $iso8601Date
);

这篇关于如何将PHP DateTime对象转换为ISO字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆