【问题标题】:DateTime input convert between timezones in PHPDateTime 输入在 PHP 中的时区之间转换
【发布时间】:2014-03-12 20:07:36
【问题描述】:

我有一个获取当地时间的输入框

date_default_timezone_set('America/Los_Angeles');
echo "<input type='datetime-local' name='fromDate' class='dates'>";

当我在输入中输入12-31-2014 10:00:00 PM

echo $_POST['fromDate'];

回复:2014-12-31T22:00:00

$test = new DateTime($_POST['fromDate']);
echo $test;

我收到2014-12-31T22:00:00 America/Los_Angeles

然后当我转换时

$from_dateGMT  = new DateTime($_POST['fromDate'], new DateTimeZone('Europe/Paris'));
$from_date = $from_dateGMT->format('Y-m-d\TH:i:s');
echo $from_date;

我收到2014-12-31T22:12:00 UTC,与上面列出的时间相同,应该增加 8 小时。

我做错了什么?

我从不处理 PHP 中的日期/时间,所以这对我来说是一次学习经历。

【问题讨论】:

  • 该错误可能是因为您试图在 string 上下文中使用DateTime object。但是您的问题 alone 中的代码行不应导致该错误。请显示更多代码。 (另外,看看this similar question。)
  • 你是对的,这是一个格式问题。我已经解决了这个问题,但它现在没有转换。我会更新上面的信息。
  • 更新了上面的代码和问题。
  • 做了一些额外的修改

标签: php datetime timezone


【解决方案1】:

也许这会起作用

$test = new DateTime($_POST['fromDate'], new DateTimeZone('America/Los_Angeles'));
$test->setTimezone(new DateTimeZone('Europe/Paris'));
echo $test->format('Y-m-d\TH:i:s');

至少这是 php 手册中的操作方式:http://us2.php.net/manual/en/datetime.settimezone.php

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 1970-01-01
    • 2013-03-15
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    相关资源
    最近更新 更多