我一直在試圖解決這個問題,並花了好幾個小時才找到這種情況繼續發生的原因。致命錯誤:帶有消息'DateTimeZone ::?的未捕獲異常'Exception'
我真的不知道我在做什麼錯!
我想在PHP中使用時區創建一個簡單的時差。我需要允許用戶在頁面上選擇這兩個位置。爲此,我使用兩個下拉列表,其中將包含所有時區。
每次我在我的服務器上運行的代碼/頁,我得到這個錯誤:
Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (origin_tz)' in /home/a1385482/public_html/timediff.php:204
Stack trace:
#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} thrown in /home/a1385482/public_html/timediff.php on line 204
以下是完整的頁面代碼:
<?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個小時。
請停止發佈噸無關碼。將其降低到重現問題所需的最低限度。 – deceze
您使用2個字符串調用'get_timezone_offset'。我不認爲''origin_tz''是一個有效的時區。 –
@deceze,爲什麼它是不相關的代碼?我使用完全相同的代碼(而不是無關代碼),並且完全相同的代碼會產生錯誤/問題! –