我无法使用PHP获得客户的时间。我只使用以下时间获取服务器时间:
$cur_time = date('d-m-Y h:i:s A');
如何解决此问题?
有人说“您可以使用时区对其进行修复”。但是我该怎么办?
我想不使用JavaScript来解决此问题。
答案 0 :(得分:0)
您首先需要一些JavaScript才能获取浏览器的时区
然后使用您的php脚本中的时区来计算浏览器所在的当前时间。
$tz = new DateTimeZone($browser_tz);
$dt = new DateTime();
$dt->setTimezone($tz);
$cur_time = $dt->format("d-m-Y h:i:s A");
答案 1 :(得分:0)
如果您只想使用PHP来实现此目的:
MaxMind的开发人员:https://dev.maxmind.com/geoip/
代码:
<?php
if(!isset($_COOKIE['timezone'])){
$ip = $_SERVER['REMOTE_ADDR'];
//Open GeoIP database and query our IP
$gi = geoip_open("GeoLiteCity.dat", GEOIP_STANDARD);
$record = geoip_record_by_addr($gi, $ip);
//If we for some reason didnt find data about the IP, default to a preset location.
//You can also print an error here.
if(!isset($record))
{
$record = new geoiprecord();
$record->latitude = 59.2;
$record->longitude = 17.8167;
$record->country_code = 'SE';
$record->region = 26;
}
//Calculate the timezone and local time
try
{
//Create timezone
$user_timezone = new DateTimeZone(get_time_zone($record->country_code, ($record->region!='') ? $record->region : 0));
setcookie("timezone", $user_timezone, time() + (86400 * 30), "/"); //setting cookie to the browser for reference
//Create local time
$user_localtime = new DateTime("now", $user_timezone);
$user_timezone_offset = $user_localtime->getOffset();
}
//Timezone and/or local time detection failed
catch(Exception $e)
{
$user_timezone_offset = 7200;
$user_localtime = new DateTime("now");
}
echo 'User local time: ' . $user_localtime->format('H:i:s') . '<br/>';
echo 'Timezone GMT offset: ' . $user_timezone_offset . '<br/>';
}
?>
<script type="text/javascript">
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
if(getCookie('timezone')!=Intl.DateTimeFormat().resolvedOptions().timeZone){
document.cookie = "timezone="+Intl.DateTimeFormat().resolvedOptions().timeZone;
location.reload();
}
</script>
注意:PHP代码可能并非一直有效。上面编写的JavaScript代码将确保PHP提取的时区与浏览器的时区匹配,否则,它将更新Cookie中的时区信息并重新加载页面。