以下代码适用于IE8以外的任何浏览器。我正在从服务器上花时间尝试在IE8中显示日期字符串和服务器小时。我得到的是字符串,serverHour,未定义未定义未定义未定义,并且对于小时,testHours,我得到nan。我已经尝试使用moment.js来显示日期,但我得到了相同的结果。任何指导将不胜感激。我尝试过几种不同的方式重新格式化日期字符串,但我无法找到有效的组合。我必须遗漏一些非常基本的东西。
var xmlHttp;
var offset = 0;
var today = new Date();
/*
return the standard time timezone offset regardless of whether the current time is on standard or daylight saving time.
http://www.webdeveloper.com/forum/showthread.php?228309-Getting-server-date-time-with-no-server-side-script
*/
Date.prototype.stdTimezoneOffset = function () {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
/*
Determine if the current time is on daylight saving time or not. We simply compare the current timezone offset with the standard one.
If they are equal then the current time is standard time. If they are not then the current time is daylight saving time. This second
method will return true when the current time is daylight saving time and false when it is standard time.
http://www.webdeveloper.com/forum/showthread.php?228309-Getting-server-date-time-with-no-server- side-script
*/
Date.prototype.dst = function () {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
// Convert GMT server time to Pacific time and return date.
function getServerTime(serverDateMs,offset) {
var date = new Date(serverDateMs + offset * 3600 * 1000);
return date;
}
// Function to get server time in GMT
function srvTime() {
// Create an XML object to collect information from server
try {
//FF, Opera, Safari, Chrome
xmlHttp = new XMLHttpRequest();
}
catch (err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err3) {
//AJAX not supported, use CPU time.
alert("AJAX not supported");
}
}
}
// Request information from the server using XML object
xmlHttp.open('POST', window.location.href, false);
xmlHttp.send();
return xmlHttp.getResponseHeader("Date");
}
// Set offset if daylight savings time or standard time
if (today.dst() == true) { offset = -7; }
else { offset = -8; }
var x = srvTime();
//i have: Fri, 02 Jan 2015 22:54:05 GMT
// modify the string to remove comma and GMT
var dateString = x.replace(",", "").replace("GMT", "");
var a = dateString.split(" ");
//I want: Nov 06 2012 23:29:33 +0000
// reorganize to match above format
var newDatString = a[2] + " " + a[1] + " " + a[3] + " " + a[4];
// create the date object
var serverT = new Date(newDatString);
// get date/time in milliseconds
var serverDateMs = serverT.getTime();
// convert GMT time to pacific time
var serverDatePacific = getServerTime(serverDateMs, offset);
// create date object from pacific time
var serverHour = new Date(serverDatePacific);
// get hours from pacific time date object
var testHour = serverHour.getHours();
答案 0 :(得分:0)
很难测试你的代码,因为你没有说哪个变量转到&#34;输出&#34; (输出将是代码中显示NaN
)
但是对变量进行了测试,并意识到问题出在你的XMLHttpRequest
上。
XMLHttpRequest
&#39; POST&#39;像这样返回标题(没有数据标题):
Keep-Alive: timeout=5, max=100
Content-Type: text/html
Content-Length: 3119
Last-Modified: Sun, 04 Jan 2015 03:38:27 GMT
但是使用HEAD
方法,返回如下:
Date: Sun, 04 Jan 2015 03:41:30 GMT
Server: Apache/2.4.3 (Win64)
Last-Modified: Sun, 04 Jan 2015 03:41:28 GMT
Accept-Ranges: bytes
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html
但这不是解决方案,因为HEAD不会阻止缓存和&#34;同步模式&#34;是&#34;坏&#34;。
如果我理解你的代码,你想要在没有Python,PHP,Ruby等解释器语言的情况下获得服务器时间,最好的方法是使用Ajax(异步)。
工作人员之外的同步
XMLHttpRequest
正在从网络平台中移除,因为它对最终用户的体验有不利影响。 (这是一个需要很多年的漫长过程。)当JavaScript全局环境是文档环境时,开发人员不得为async参数传递false。强烈建议用户代理在开发人员工具中警告这种用法,并尝试在发生时抛出InvalidAccessError异常。阅读:http://xhr.spec.whatwg.org/
使用&#34;异步模式&#34;,像这样:
xmlHttp.open('HEAD', URL, true);//true = async
xmlHttp.onreadystatechange = function () { ... };
The HEAD method与GET相同,只是服务器不能在响应中返回消息体。响应HEAD请求的HTTP头中包含的元信息应该与响应GET请求时发送的信息相同。该方法可用于获得关于请求所暗示的实体的元信息,而无需转移实体主体本身。此方法通常用于测试超文本链接的有效性,可访问性和最近的修改。
所以你可以使用getback为get Date创建一个函数,并使用new Date().getTime()
来防止缓存:
function getDateFromServer(done, fail) {
var xmlHttp, uri, dateHeader;
if (window.XMLHttpRequest) {
xmlHttp = new window.XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttp = new window.ActiveXObject("Msxml2.XMLHTTP");
} catch (ee1) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (ee2) {
fail(-1, ee2.message);
return;
}
}
} else {
fail(-1, "Your browser don't support XMLHttpRequest");
return;
}
uri = String(window.location);//Get same origin
uri += uri.indexOf("?") !== -1 ? "&_=" : "?_=";
uri += new Date().getTime();//Prevent cache
xmlHttp.open("HEAD", uri, true);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
dateHeader = xmlHttp.getResponseHeader("Date");
if (dateHeader) {
done(dateHeader);
} else {
fail(xmlHttp.status, "Date header is undefined");
}
}
};
xmlHttp.send(null);
}
此函数有两个参数,第一个参数在ajax头返回日期时运行,第二个参数在连接到服务器或ISP时出错时运行。
使用代码(注意这是异步,需要回调):
getDateFromServer(function (x) {//First argument is "done" callback
alert(x);
//put your code
}, function(status, msg) {//Second argument is "fail" callback
alert("Error in request, error: " + status + " / " + msg);
});
jsfiddle中的示例:http://jsfiddle.net/9cy9kvsk/