因此,如果我有一个像这样的字符串:'2017-12-01T16:03:00' 并且需要将此字符串转换为 的时区America/New_York
,如何转换此字符串?不完全确定T
字符串中正在做什么以及它的确切用途。
我很好奇正确的方法,虽然我相信T
这里很重要,但我理解它的目的。到目前为止我在这里尝试过的:
$string = '2017-12-01T16:03:00';
$time_fix = explode('T', $string);
if (count($time_fix) > 1)
{
$data_date = DateTime::createFromFormat('Y-m-d H:i:s', $time_fix[0] . ' ' . $time_fix[1]);
$output = $data_date->format('Y-m-d H:i:s', new DateTimeZone('America/New_York'));
} else {
$data_date = DateTime::createFromFormat('Y-m-d H:i:s', $time_fix[0] . ' 00:00:00');
$output = $data_date->format('Y-m-d H:i:s', new DateTimeZone('America/New_York'));
}
不确定这是否正在转换时区,所以想知道您对此有何想法?请问$output
变量包含的日期和时间America/New_York
时区?对此进行测试非常困难,因为我不知道创建时间字符串时当前所在的时区。
另外,想知道这里的 T 是否重要以及它的含义。以及如何针对America/New_York
时区正确执行此操作?
更新
显然,我发现通过 API 创建这些日期字符串的服务器时区已经在东部标准时间。但如果我不知道这一点,它将如何转换为 UTC?API 的开发人员声明它是 8601 格式的 UTC,但时区是 EST。这对我来说没有意义。因为,我相信 EST 是 UTC-5,而不仅仅是 UTC。我到底应该怎么从 API 处理不当的 UTC 时区字符串结果中知道这一点?我是否正确地指出这2017-12-01T16:03:00
不是 UTC 时区中 EST 时区的正确字符串?
如果你这样做:
$date = new DateTime($info['CreateDate']);
$date->setTimeZone(new DateTimeZone('UTC'));
$date->setTimeZone(new DateTimeZone('America/New_York'));
$output = $date->format('Y-m-d H:i:s');
您首先在默认时区中创建 DateTime 对象,这将影响时间戳计算,然后更改时区。相反,假设 UTC 输入,你应该这样做:
$date = new DateTime($info['CreateDate'], new DateTimeZone('UTC'));
$date->setTimeZone(new DateTimeZone('America/New_York'));
$output = $date->format('Y-m-d H:i:s');
这样 DateTime 对象会将输入日期解释为 UTC 时间并正确计算时间戳。然后设置时区只是为了获取正确的日期字符串,它不会影响底层时间戳。
我注意到 ISO 8601 日期字符串可以指定 UTC 偏移量,因此在这种特殊情况下,您可能会在没有指定它的情况下逃脱,因为没有给出偏移量。如果您的默认时区是 UTC,这在这种情况下也没有区别。
根据新数据编辑:
如果您知道输入位于东部标准时区,请尝试更改构造 DateTime 对象的行。
$date = new DateTime($info['CreateDate'], new DateTimeZone('EST'));
$date->setTimeZone(new DateTimeZone('America/New_York'));
$output = $date->format('Y-m-d H:i:s');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句