我想自动检测访问者时区,因此显示的日期和时间反映了他们当前的时间。我意识到单独使用PHP是不可能的,但也需要一些JavaScript。
我可以使用哪些内容替换下面代码中$timezone
的值来自动检测访问者时区?
<?php
// Date & time format.
$date_format = "m/d/Y";
$time_format = "h:i A";
$timezone = "America/New_York";
// Get current datetime.
$date = new DateTime();
// Set timezone.
$date->setTimezone(new DateTimeZone($timezone));
// Echo current date and time.
echo $date->format($date_format . " " . $time_format);
?>
返回:
07/22/2014 03:03 PM
答案 0 :(得分:2)
使用java脚本可以使用它
<script src='http://code.jquery.com/jquery-2.1.1.js'></script>
<script src="https://bitbucket.org/pellepim/jstimezonedetect/raw/f9e3e30e1e1f53dd27cd0f73eb51a7e7caf7b378/jstz.min.js"></script>
<script>
$(document).ready(function(){
var timezone = jstz.determine();
$("#div").html(timezone.name());
});
</script>
<div id='div'></div>
请记住下载jstz.min.js它不允许从https://bitbucket.org/嵌入 如果你想看到它工作giv一看 http://gomusic.designerbh.com/teste.php
答案 1 :(得分:1)
最好使用Javascript
请参阅此fiddle以获取示例
jQuery(document).ready(function() {
var foo = jQuery('#foo');
function updateTime() {
var now = new Date(),
d = [];
d[0] = now.getFullYear().toString(),
d[1] = now.getMonth()+1, //months are 0-based
d[2] = now.getDate(),
d[3] = now.getHours(),
d[4] = now.getMinutes();
//doing YY manually as getYear() is deprecated
//remove the next line if you want YYYY instead of YY
d[0] = d[0].substring(d[0].length-2); //not using substr(-2) as it doesn't work in IE
//leading zeroes
for (var i=1; i<=4; i++)
if (d[i] < 10) d[i] = '0' + d[i];
foo.val(d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4]);
}
updateTime();
setInterval(updateTime, 5000); // 5 * 1000 miliseconds
});