2015-01-02 2 views
3

아래의 코드는 IE8을 제외한 모든 브라우저에서 잘 작동합니다. 나는 서버에서 시간을내어 IE8에서 날짜 문자열과 서버 시간을 표시하려고합니다. 내가 얻는 것은 serverHour라는 문자열에 대한 것이다. undefined undefined undefined undefined, 그리고 몇 시간 동안, testHours, 나는 nan을 얻는다. moment.js를 사용하여 표시 할 날짜를 얻으려고했지만 동일한 결과를 얻습니다. 모든 지침은 크게 감사하겠습니다. 날짜 문자열을 여러 가지 방법으로 다시 포맷하려고했지만 작동하는 조합을 찾을 수 없습니다. 나는 아주 기본적인 것을 놓치고 있어야합니다.자바 날짜가 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

(이 비동기 필요 콜백됩니다주의) 코드를 사용

? – Jack

+0

'window.location.href.toString()'에 문제가있을 수 있습니까? http://stackoverflow.com/questions/9466156/tostring-does-not-work-in-ie –

+0

serverDateMS는 서버 시간/밀리 초로 변환 된 날짜입니다. 이후 클라이언트에 대한 ie8에 표시 할 서버 정보를 얻을 수 없으므로 테스트 할 함수를 호출하지 않았습니다. – vadorian

답변

0

(출력 NaN을 표시 코드의 위치 것)는 "출력"로 이동하는 변수 말을하지 않았기 때문에, 코드를 테스트하기 어렵다 그러나 함께 테스트를했다 변수 및 귀하의 XMLHttpRequest 함께 문제가 실현. (데이터 헤더 제외)이 같은 "POST"리턴 헤더

XMLHttpRequest :

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 이유는

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

그러나 HEAD 방법을 사용하여, 다음과 같이 반환 캐시를 방지하지 말고 "동기화 모드"가 "불량"입니다.

파이썬, PHP, 루비 등의 인터프리터 언어없이 서버 시간을 얻고 싶다면 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 서버가 응답 메시지에 Message-Body를 반드시 리턴해야한다는 것 이외에는 GET과 동일하다. HEAD 요청에 대한 응답으로 HTTP 헤더에 포함 된 메타 정보는 GET 요청에 대한 응답으로 전송 된 정보와 동일해야합니다 (SHOULD). 이 방법은 엔티티 본문 자체를 전송하지 않고 요청에 의해 암시 된 엔티티에 대한 메타 정보를 얻는 데 사용할 수 있습니다. 이 메소드는 유효성, 액세스 가능성 및 최근 수정에 대한 하이퍼 텍스트 링크를 테스트하는 데 자주 사용됩니다.

그래서 당신은 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); 
} 

이 함수는 두 개의 인수, 첫 번째 인수 실행이있을 때 아약스 헤더 반환 날짜와 두 번째 인수 실행 서버 또는 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); 
}); 

예 : serverDateMs``무엇 http://jsfiddle.net/9cy9kvsk/

+0

나는 당신의 기능을 시험해 보았는데 나는 결과가 혼란 스럽다. 전역 변수 테스트를 선언하고 아래와 같이 getDateFromServer 함수를 호출했습니다. getDateFromServer은 (함수 (X) {// 먼저 인수 시험 = 새로운 날짜 (X) .toUTCString() 콜백 "완료"된다 } 함수 (상태) {// 두 번째 인수는 콜백 "실패"이다 알림 ('요청 오류, 오류 :'+ 상태); }); 사용하는 경우 document.write ("서버 시간 :"+ test + "
"); 보통 나는 정의되지 않았지만 때로는 기대하는 문자열을 얻습니다. 변수에 대해 더 많은 것을하고 싶습니다. pacifictiem로 변환하십시오. 그럴 수있어? – vadorian

+0

한 개의 댓글이 더 있습니다. 테스트 변수는 이제 ie11에 정의되지 않은 것으로 표시됩니다. 당신의 도움을 주셔서 감사합니다. – vadorian

+0

@vadorian은 첫 번째 함수 인'getDateFromServer (function (x) {** 여기에 코드를 입력하십시오 **}, function (status) {alert ("요청시 오류, 오류 :"+ 상태) –

관련 문제