首先,我为要求另一个与网络相关的时间而道歉。时区问题。我知道有很多资源和类似的问题,但我仍然无法理解php和js时间之间的时间转换是如何工作的。
所以这是我的情况。我想让服务器时间包括时区到javascript中,并在客户端进行某些操作(与此问题无关)。我有这个简短的片段不能正常工作,因为我期待它:
get_date.php
<?php
date_default_timezone_set('Romania/Bucharest');
echo date('D M d Y H:i:s');
?>
的index.html
<body>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript'>
$.get( "get_date.php", function(data) {
current = new Date(data);
alert(current);
});
</script>
</body>
警告信息
所以问题是我得到罗马尼亚的日期和时间(服务器的位置),但是柏林的偏移和时区(我访问网站的位置)。我想在Javascript中正确获取服务器时间,日期,偏移和时区,独立于用户位置。例如,警报消息应为Thu Feb 12 2015 13:26:10 GMT+0200(EET)
。
此外,欢迎任何有关为何不能按预期工作的说明!
答案 0 :(得分:3)
更改
<强> get_date.php 强>
<?php
date_default_timezone_set('Romania/Bucharest');
echo date('D M d Y H:i:s');
exit();
?>
和你的脚本文件。不要将数据传递给jquery的Date函数。
<script type='text/javascript'>
$.get( "get_date.php", function(data) {
alert(data);
});
</script>
请分享结果。
答案 1 :(得分:0)
当您使用JavaScript的日期功能时,您的浏览器将根据系统的时区设置显示日期和时间。为了防止您需要格式化服务器上的日期并将其作为字符串处理。 如果由于任何原因您必须使用javaScript日期函数,则需要通过预先计算偏移来更正日期。
答案 2 :(得分:0)
使用JavaScript的本地Date
对象是不可能的 - 它始终在客户端时区运行。
使用像Moment.js这样的库,它的扩展名为Moment Timezone。这些允许您使用JS中您喜欢的任何时区,包括解析日期和格式化它们的可能性。
答案 3 :(得分:0)
您可以使用http://json-time.appspot.com/time.json或其变种,例如http://json-time.appspot.com/time.json?tz=GMT
var currTime;
$.ajax({
type: "GET",
dataType: 'jsonp',
url: "http://json-time.appspot.com/time.json",
async: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
console.log(msg);
// currTime.tz = "UTC"
// currTime.hour = 12
// currTime.datetime = "Thu, 12 Feb 2015 12:13:39 +0000"
// currTime.minute = 13
// currTime.second = 39
}
});
这是一个PHP
脚本,您可以将其放在自己的服务器上,而不是使用json-time.appspot.com
<?php
header('Content-Type: application/json');
header("Expires: Tue, 01 Jan 1990 00:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$error = "false";
$tz = $_GET['tz'];
if ( !in_array($tz, DateTimeZone::listIdentifiers())) {
$error = 'invalid time zone';
$tz = 'UTC';
}
date_default_timezone_set($tz);
?>
<?php echo htmlspecialchars($_GET['callback'], ENT_QUOTES, 'UTF-8' ); ?>({
"tz": "<?php echo $tz ?>",
"hour": <?php echo date('G'); ?>,
"datetime": "<?php echo date(DATE_RFC2822); ?>",
"second": <?php echo intval(date('s')); ?>,
"error": "<?php echo $error; ?>",
"minute": <?php echo intval(date('i')); ?>
})
答案 4 :(得分:0)
在PHP中使用以下代码。我在我的项目中使用相同的代码来获得正确的服务器时间
<?php
date_default_timezone_set('Romania/Bucharest');
echo date('F d,Y h:i:s');
die();
?>
<body>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript'>
$.get( "get_date.php", function(data) {
current = new Date(data);
alert(current);
});
</script>
查看w3school javascript数据函数以获取字符串
的正确日期