Javascript date shows nan in ie8

The code below works well in any browser except IE8. I am taking the time from the server and trying to display the server date and time string in IE8. What I get for the string, serverHour, is undefined undefined undefined undefined, and for the testHours hours, I get nan. I tried using moment.js to display the date, but I get the same result. Any guidance would be much appreciated. I've tried reformatting the date string in a couple of different ways, but I can't seem to find a combination that works. I must be missing something very basic.

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

      

+3


source to share


1 answer


It's hard to test your code since you didn't say which variable goes to "exit" (the exit will be the place in your code that displays NaN

)

But did a test with variables and realized that the problem is related to yours XMLHttpRequest

.

XMLHttpRequest

with "POST" return headers like this (no data header):

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

      

But using the method HEAD

, let's return like this:

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

      

But this is not a solution, because HEAD does not prevent cache and "sync-mode" is "bad".

If I understand your code, you want to get the server time without an interpreter language like Python, PHP, Ruby or other, the best way to do this is using Ajax (asynchronous).

Synchronous XMLHttpRequest

Outside Workers is in the process of being removed from the web platform as it has a detrimental effect on the end user experience. (This is a lengthy process that takes many years.) Developers should not pass false for the async argument when the JavaScript global environment is the document framework. User agents are strongly encouraged to warn about this use in the developer tools and can experiment with throwing an InvalidAccessError exception when it does. Read: http://xhr.spec.whatwg.org/



Using "asynchronous mode", for example:

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

      

The HEAD method is identical to GET, except that the server MUST NOT return a message body in response. The meta information contained in the HTTP headers in response to a HEAD request MUST be identical to the information sent in response to a GET request. This method can be used to get meta information about an entity implied by a request without passing in the entity object itself. This method is often used to check hypertext links for validity, accessibility, and recent modification.

So you can create a function using a callback to get the date and use new Date().getTime()

to avoid the cache:

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

      

This function has two arguments, the first argument is triggered when the ajax header return date and the second argument is executed when you have a server or ISP connection error.

Using code (note this is asynchronous, callback needed):

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

      

Example in jsfiddle: http://jsfiddle.net/9cy9kvsk/

0


source







All Articles