1
new Date().getTimezoneOffset()*(-1);

此 JS 函数以分钟为单位返回机器的 UTC 时区。有没有任何 PHP 函数做同样的事情?
谢谢..

4

2 回答 2

1
<?php // RAY_easy_client_time.php
error_reporting(E_ALL);


// USE JAVASCRIPT TO GET THE CLIENT TIME AND COMPUTE THE OFFSET FROM THE SERVER TIME


// LOCATION OF THE SERVER - COULD BE ANYWHERE
date_default_timezone_set('America/Denver');

// DIFFERENCE OF SERVER TIME FROM UTC
$server_offset_seconds = date('Z');

// WHEN THE FORM IS SUBMITTED
if (!empty($_POST))
{
    // JAVASCRIPT TELLS US THE CLIENT TIME OFFSET FROM GMT / UTC
    $client_offset_minutes = $_POST["date_O"];
    $client_offset_seconds = $client_offset_minutes * 60;

    // THE TIME WE WANT AT THE CLIENT LOCATION
    $client_timestring = 'TODAY 7:00AM';

    // MAKE THE COMPUTATIONS, INCORPORATING THE OFFSET FROM GMT
    $client_timestamp  = strtotime($client_timestring) + $client_offset_seconds;
    $server_timestamp  = $client_timestamp + $server_offset_seconds;
    $server_timestring = date('l, F j, Y \a\t g:i a', $server_timestamp);

    echo "<br/>ACCORDING TO THE VALUE FROM PHP date Z";
    echo "<br/>SERVER IS LOCATED $server_offset_seconds SECONDS FROM UTC";
    echo "<br/>";

    echo "<br/>ACCORDING TO THE VALUE FROM JS dateObject.getTimezoneOffset()";
    echo "<br/>CLIENT IS LOCATED $client_offset_minutes MINUTES FROM UTC";
    echo "<br/>";

    echo "<br/>WHEN IT IS '$client_timestring' AT THE CLIENT, IT IS '$server_timestring' IN " . date_default_timezone_get();
}

// END OF PHP - USE HTML AND JS TO CREATE THE FORM
echo PHP_EOL; ?>

<form method="post">
<input name="date_O" id="dateTime_O" type="hidden" />
<input type="submit" value="CHECK CLIENT DATETIME" />
</form>

<!-- NOTE THIS WILL GIVE YOU THE VALUES AT PAGE-LOAD TIME, NOT AT SUBMIT TIME -->
<!-- MAN PAGE REF: http://www.w3schools.com/jsref/jsref_obj_date.asp -->
<script type="text/javascript">
var dateObject = new Date();
document.getElementById("dateTime_O").value = dateObject.getTimezoneOffset();
</script>
于 2012-12-28T18:14:24.480 回答
1

PHP 作为服务器端,只能读取客户端发送的内容。如果没有用户(或浏览器等用户代理)明确告知,它无法告知用户时区。

有几种猜测方法。您可以通过调用位置服务来查找 IP 并根据 IP 位置猜测时区(时间昂贵并且可能返回不正确的结果,我不推荐它)。

您还可以让您的 javascript 进行 ajax 调用以告诉服务器该值Date().getTimezoneOffset()是什么。我个人会走这条路。

于 2012-12-28T18:17:49.297 回答