www.webdeveloper.com
Results 1 to 9 of 9

Thread: Getting "undefined" when trying to use getMonth on date acquired via AJaX

  1. #1
    Join Date
    Dec 2002
    Location
    St. Louis, MO, USA
    Posts
    1,582

    Red face Getting "undefined" when trying to use getMonth on date acquired via AJaX

    Hello, everyone.

    I'm trying to implement a script that will display both the user's local time and the time in St. Louis (based off of the server clock; I want to convert it to UTC, then subtract the hours based upon DST, either -5 or -6.) But I'm hitting a slight snag.

    As far as the local time, that's a two-inch putt. I'm grabbing the datetime from the user's computer, and manually formatting it to look like:
    Your Time: Friday, December 16, 2011 - 08:35:00 PM

    I'm using AJaX to get the time from the server using return xmlHttp.getResponseHeader("Date"); and the hours, minutes, and seconds are fine, as is the year. But when I try to use getMonth() and getDay(), the values are coming back as "undefined". I'm assuming because they are expecting integers, but receiving text.

    So, how can I retrieve the month and day-of-week from my AJaX?

    Thanks,
    |||||
    o . Q
    ___ "You live and you learn; or you don't live long." - Lazarus Long

    ^_^

  2. #2
    Join Date
    Feb 2006
    Posts
    2,926
    Did you convert the date string into a date object, before using the methods?

  3. #3
    Join Date
    Dec 2002
    Location
    St. Louis, MO, USA
    Posts
    1,582
    First, I am accessing a function that returns the value of the date via AJaX, like so:
    Code:
    var xmlHttp;
    function srvTime(){
    	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) { err3 = "";
    			}
    		}
    	}
    	xmlHttp.open('HEAD',window.location.href.toString(),false);
    	xmlHttp.setRequestHeader("Content-Type", "text/html");
    	xmlHttp.send('');
    	return xmlHttp.getResponseHeader("Date");
    }
    This function is being called from within the function that displays the date/time by writing to two divs (one for user time, one for server time), like so:
    Code:
    		$st = srvTime();
    		$srvrCurrentTime = new Date($st);
    Then I am attempting to use getMonth() and getDay() from $srvrCurrentTime.
    |||||
    o . Q
    ___ "You live and you learn; or you don't live long." - Lazarus Long

    ^_^

  4. #4
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    Simpler still.... in the web page have php write in a date string that is immediately evaluated in to a date object

    Code:
    serverTimeObject = new Date("<?= date("r");?>");
    Then a routine added to keep track of the times. If you search the forums here, you will find examples of such script and please DONT USE setTimeout if your using a timer that repeats at a regular interval, you use setInterval which is only set once and will repeat at the specified timer interval.

    If your looking to get the date and time, return a time string which will already be formatted with the day of week name, date, month name, year, time and any offset, all you do is strip that information out of the string.
    We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
    Code:
    Youre = {
          STILL_not_getting_it:function(){
               alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
          },
          MissingThePoint:function(msg){
                alert("You're missing the point. " + msg);
          }
    }
    Youre.STILL_not_getting_it();

  5. #5
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    Example:-
    PHP Code:
    <?php

        $serverTimeRef 
    date("r"); // we will grab an RFC type time string to use in the site
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Today [ <?php echo $serverTimeRef;?> ]</title>
    <script>
    itimer = {
        started:new Date().getTime(),
        server:new Date("<?php echo $serverTimeRef?>").getTime(),
        tick:function(){
            itimer.milli = new Date().getTime();
            itimer.diff = itimer.milli - itimer.started;
            itimer.serverSync = itimer.server + itimer.diff;
            document.getElementById("serv").value = new Date( itimer.serverSync ).toGMTString();
            document.getElementById("loca").value = new Date( itimer.milli ).toGMTString();
        },
        auto:setInterval("itimer.tick()",1000)
    }
    </script>
    </head>
    <body><div>Server: <input name="serv" id="serv" size="30" value=""><br />
    Local: <input name="loca" size="30" id="loca" value=""></div>
    </body>
    </html>
    My server is 10 seconds faster than my local machines time and seeing as the host I use provides server times synced with GMT, its more likely my machine is 10 seconds slow.
    We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
    Code:
    Youre = {
          STILL_not_getting_it:function(){
               alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
          },
          MissingThePoint:function(msg){
                alert("You're missing the point. " + msg);
          }
    }
    Youre.STILL_not_getting_it();

  6. #6
    Join Date
    Dec 2002
    Location
    St. Louis, MO, USA
    Posts
    1,582
    So there's no way to get the month and day from the datestring acquired via AJaX?

    Please don't take this the wrong way. I appreciate your suggestion. But you assume that I'm using a server-side language like PHP.

    Granted, I _am_ using a server-side language, but your solution automatically assumed that I did. My question specifically targeted an AJaX methodology. If I were searching for a server-side solution, I would have posted my question in the appropriate forum.

    Is there a way to get the month and day from the datestring being acquired via AJaX?

    Thanks,
    Last edited by WolfShade; 12-17-2011 at 02:19 PM.
    |||||
    o . Q
    ___ "You live and you learn; or you don't live long." - Lazarus Long

    ^_^

  7. #7
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    785
    I tried your code like this, removing the timezone bias, so it should be returning a Date object in GMT.
    And I was able to pull all the properties needed to format the time you want to display.

    Code:
    function srvTime()
    {
    	var xmlHttp, date;
    	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) { err3 = "";
    			}
    		}
    	}
    	xmlHttp.open('HEAD', window.location.href, false);
    	xmlHttp.setRequestHeader("Content-Type", "text/html");
    	xmlHttp.send('');
    
    	date = new Date(xmlHttp.getResponseHeader('Date'));
    	return new Date(date.getTime() + (date.getTimezoneOffset() * 60000));
    }
    
    var x = srvTime();
    alert(
    	x.getMonth()    + ' ' +
    	x.getDate()     + ' ' +
    	x.getFullYear() + ' ' +
    	x.getHours()    + ':' +
    	x.getMinutes()  + ':' +
    	x.getSeconds()
    );
    Are the date formats returned by the server always in the same format? Mine was (at the time)... Sat, 17 Dec 2011 20:56:08 GMT

  8. #8
    Join Date
    Dec 2002
    Location
    St. Louis, MO, USA
    Posts
    1,582
    I will give your suggestion a shot, bionoid.

    I think what is returned depends upon browser. I've seen Sat, 17 Dec 2011 20:56:08 CDT, and I've seen Sat, 17 Dec 2011 20:56:08 [Central Daylight Time] -0600 without using getTimezoneOffset.

    Much appreciated.
    |||||
    o . Q
    ___ "You live and you learn; or you don't live long." - Lazarus Long

    ^_^

  9. #9
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    You have ajax request a get from a server-side.php script that returns the server time as a string, that string is bes as an RFC type because the javascript Date() object understands RFC date formats. From that you can grab the month, hour or whatever you want.

    My other suggestion was suggested because its the simplest method, get the date and time set by the server in the page delivery and have the client side keep track. It also saves on transactions meaning less of a server load.
    We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
    Code:
    Youre = {
          STILL_not_getting_it:function(){
               alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
          },
          MissingThePoint:function(msg){
                alert("You're missing the point. " + msg);
          }
    }
    Youre.STILL_not_getting_it();

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles