【问题标题】:Converting the a date value (String) to timestamp with a different timezone将日期值(字符串)转换为具有不同时区的时间戳
【发布时间】:2016-12-10 12:08:50
【问题描述】:

我有一个这样的日期值:

$date_value = "2016-12-10 11:28:36";

我的 TimeZone 是 Asia/Tehran,它与 GMT 有 3:30 的偏移量(因此它变成了 GTM3:30+)。我将我的内容保存在 14:58,但它使用上述值 ($date_value) 保存项目,这听起来合乎逻辑,因为它使用了与 GMT (GMT00) 没有偏移的服务器时区。

现在,我想将日期转换回我想要的时区“亚洲/德黑兰”,但我的日期程序没有按预期工作(“预期”是指它不会将日期时间转换回 14: 59:00) 这是德黑兰的时间。这是我使用的代码:

$DateTime = new DateTime($date_value, new DateTimeZone("Asia/Tehran"));

print $DateTime->format($format); // edited the question with on this line

但它会打印出确切的日期,就好像没有变化一样。

它总是有效,但我不知道为什么它不适用于这种特定情况。我在这里做错了什么?

【问题讨论】:

  • 怎么不行?
  • 编辑了问题。
  • 是的,我的错。我的意思是格式()
  • 我不太熟悉时区,但也许format 没有考虑时区?如果您使用$format = 'd.m.Y H:i:sP';,您可以看到有正确的+03:30 值。

标签: php date datetime


【解决方案1】:

如果您从服务器检索到的日期字符串是 UTC,您应该在 UTC 中构造您的 DateTime 对象,然后更改时区。

$format = "Y-m-d H:i:s";
$date_value = "2016-12-10 11:28:36";

$DateTime = new DateTime($date_value, new DateTimeZone("UTC"));
$DateTime->setTimezone(new DateTimeZone("Asia/Tehran"));
print $DateTime->format($format);

// Outputs: 2016-12-10 14:58:36

【讨论】:

  • 键是“UTC”。非常感谢
【解决方案2】:

从字符串创建 DateTime 对象:

$date_value = "2016-12-10 11:28:36";
$date = new DateTime($date_value);

设置时区:

$date->setTimezone(new DateTimeZone("Asia/Tehran"));

获取并格式化日期:

echo $date->format('Y-m-d H:i:s (e) P') . "\n";

此代码显示了在 DateTime 对象中更改时区时它是如何工作的:

<?php
$date_value = "2016-12-10 11:28:36";

$date = new DateTime($date_value);
$date->setTimezone(new DateTimeZone("Asia/Tehran"));
echo $date->format('Y-m-d H:i:s (e) P') . "\n";

$date->setTimezone(new DateTimeZone('Europe/Warsaw'));
echo $date->format('Y-m-d H:i:s  (e) P') . "\n";

输出:

2016-12-10 22:58:36 (Asia/Tehran) +03:30
2016-12-10 20:28:36  (Europe/Warsaw) +01:00

您可以在此处阅读更多信息:http://php.net/manual/en/datetime.settimezone.php

(您的代码不起作用,因为 DateTime 构造函数方法中的 timezone 参数在此指定时区创建日期)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-17
    • 2023-03-27
    • 1970-01-01
    • 2011-03-19
    • 2011-05-05
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多