2015-01-02 45 views
3

下面的代碼在除IE8以外的任何瀏覽器中都能正常工作。我正在從服務器獲取時間,並嘗試在IE8中顯示日期字符串和服務器小時。我得到的是字符串serverHour,undefined undefined undefined undefined,對於小時,testHours,我得到了nan。我曾嘗試使用moment.js來獲取顯示日期,但我得到了相同的結果。任何指導將不勝感激。我試過用不同的方式重新設置日期字符串的格式,但是我找不到能夠工作的組合。我必須錯過一些非常基本的東西。Javascript日期顯示nan在ie8

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(); 
+4

什麼是'serverDateMs'? – Jack

+0

可能有'window.location.href.toString()'的問題? http://stackoverflow.com/questions/9466156/tostring-does-not-work-in-ie –

+0

serverDateMS是服務器時間/日期轉換爲毫秒。由於我無法得到任何服務器信息顯示在ie8客戶端我停止調用函數來測試。 – vadorian

回答

0

很難對代碼進行測試,因爲你沒有說哪個變量轉移到「輸出」(輸出將是你的代碼顯示NaN位置)

但是做了一個測試用變量並意識到問題出在你的XMLHttpRequest

XMLHttpRequest與 'POST' 返回報頭是這樣的(沒有數據報頭):使用HEAD方法

Keep-Alive: timeout=5, max=100 
Content-Type: text/html 
Content-Length: 3119 
Last-Modified: Sun, 04 Jan 2015 03:38:27 GMT 

但是,返回這樣的:

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不要阻止緩存,「同步模式」是「壞」。

如果我理解您的代碼,您希望在不使用解釋器語言(如Python,PHP,Ruby或其他語言)的情況下獲得服務器時間,則最好的方法是使用Ajax(異步)。

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs. Read: http://xhr.spec.whatwg.org/

使用「異步模式」,是這樣的:

xmlHttp.open('HEAD', URL, true);//true = async 
xmlHttp.onreadystatechange = function() { ... }; 

The HEAD method是相同,除了在應答服務器不能返回一個消息體得到的。響應HEAD請求的HTTP頭中包含的元信息應該與響應GET請求發送的信息相同。此方法可用於獲取有關請求隱含的實體的元信息,而無需傳遞實體主體本身。此方法通常用於測試超文本鏈接的有效性,可訪問性和最近的修改。

所以,你可以使用回調獲取日期創建功能和使用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。

使用的代碼(注意,這是異步,需要回調):在的jsfiddle

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); 
}); 

例子:http://jsfiddle.net/9cy9kvsk/

+0

我試過你的功能,結果不一樣。我聲明瞭一個全局變量測試,並調用getDateFromServer函數,如下所示。 getDateFromServer(函數(X){//第一個參數是 「完成」 回調 測試=新日期(x)的.toUTCString(); },功能(狀態){//第二個參數是 「失敗」 回調 警報(「請求錯誤,錯誤:」+狀態); }); 當使用我document.write(「服務器時間是:」+測試+「
」); 我通常會得到未定義的,但有時會得到我期望的字符串。我想對變量做更多的事情。轉換爲太平洋。我可以嗎? – vadorian

+0

還有一點評論。測試變量現在在ie11中顯示未定義。謝謝你的幫助。 – vadorian

+0

@vadorian把你的代碼放到第一個函數getDateFromServer(function(x){** PUT YOUR CODE HERE **},function(status){alert(「Error in request,error:」+ status);});'' –