0

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

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

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

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

致命错误:/home/a1385482/public_html/timediff.php:204 中带有消息“DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (origin_tz)”的未捕获异常“Exception”

堆栈跟踪:

#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 个小时。

4

1 回答 1

4

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

我想你想要:

$offset = get_timezone_offset($timezone1, $timezone2);
于 2013-08-21T18:29:42.777 回答