【问题标题】:Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::?致命错误:未捕获的异常 'Exception' 带有消息 'DateTimeZone::?
【发布时间】:2013-08-24 06:27:12
【问题描述】:

我一直在尝试解决这个问题,并花了几个小时来寻找为什么这种情况一直发生但无济于事。

我真的不知道自己做错了什么!

我正在尝试使用 PHP 中的时区创建一个简单的时差。我需要允许用户选择页面上的两个位置。为此,我使用了两个下拉列表,其中包含所有时区。

每次我在服务器上运行代码/页面时,都会收到此错误:

致命错误:/home/a1385482/public_html/timediff.php:204

堆栈跟踪:

#0 /home/a1385482/public_html/timediff.php(204): DateTimeZone->__construct('origin_tz')

#1 /home/a1385482/public_html/timediff.php(215): get_timezone_offset('origin_tz', 'remote_tz')

#2 {main} 在第 204 行的 /home/a1385482/public_html/timediff.php 中抛出

这是完整的页面代码:

<?php
echo "Version: " . phpversion();
?> 

<form method="post" action="">
  <select name="timezone2" id="timezone2" class="timezone2">
    <option value="Pacific/Midway">(GMT-11:00) Midway Island, Samoa</option>
    .. snip ..
</select>
  <select name="timezone1" id="timezone1" class="timezone1">
    <option value="Pacific/Midway">(GMT-11:00) Midway Island, Samoa</option>
    .. snip ..
  </select>
<input type="submit" name="submit" value="send"/>

</form>


<?php
if( isset($_POST['submit']))
{
    //be sure to validate and clean your variables
    $timezone1 = htmlentities($_POST['timezone1']);
    $timezone2 = htmlentities($_POST['timezone2']);

    //then you can use them in a PHP function. 
    function get_timezone_offset( $origin_tz, $remote_tz ) {
          $timezone1 = new DateTimeZone( $origin_tz );
          $timezone2 = new DateTimeZone( $remote_tz );

          $datetime1 = new DateTime("now", $timezone1);
          $datetime2 = new DateTime("now", $timezone2);

          $offset = $timezone1->getOffset($datetime1) - $timezone2->getOffset($datetime2);
          return $offset;
    
    }

    $offset = get_timezone_offset('origin_tz', 'remote_tz');
    echo $offset/3600;
}

?>

由于我在这个问题上卡了将近 8 个小时,所以请有人解释一下。

【问题讨论】:

  • 请停止发布大量不相关的代码。将其减少到重现问题所需的最低限度。
  • 您使用 2 个字符串调用 get_timezone_offset。我不认为'origin_tz' 是一个有效的时区。
  • @deceze,为什么它是不相关的代码?!我正在使用完全相同的代码(不是不相关的代码)并且完全相同的代码会产生错误/问题!
  • 使用一些常识判断,好吗?数百个几乎相同的 HTML 元素:不需要,一个小样本就可以了。实际执行与问题相关的操作的实际代码:必要。
  • htmlentities 仅应在回显到屏幕上时使用。这不是为了清理输入。

标签: php


【解决方案1】:

您将 'origin_tz' 和 'remote_tz' 传递给不是有效时区的构造函数,请参见此处:http://www.php.net/manual/en/timezones.php

我想你想要:

$offset = get_timezone_offset($timezone1, $timezone2);

【讨论】:

  • 我也试过了!我在中得到未知或错误时区($timezone1)'
  • @Simon 你是通过get_timezone_offset($timezone1, ...) 还是get_timezone_offset('$timezone1', ...)?! (注意引号。)
  • @deceze,哇,原来是这样...我用引号传递了它!它可以在没有引号的情况下使用。
  • @Simon 很高兴它成功了。顺便说一句,学习阅读错误消息和堆栈跟踪。错误消息和DateTimeZone-&gt;__construct('origin_tz') 清楚地表明您正在传递值“origin_tz”(以及后来的“$timezone1”)。这应该会敲响警钟并让您自己找到错误。
  • @deceze,当然。欣赏它。
猜你喜欢
  • 2012-04-25
  • 2014-03-17
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 2016-07-09
  • 2012-05-06
  • 2012-03-14
相关资源
最近更新 更多