www.webdeveloper.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 38

Thread: Servertime Count problem

Hybrid View

  1. #1
    Join Date
    Oct 2011
    Posts
    11

    Angry Servertime Count problem

    <script type="text/javascript">
    //Get time in Js
    var sTime = "<?php echo date("G:i:s"); ?>";

    function fixTime()
    {
    // Fix hours.
    if (sTime.substr(1, 1) == ":")
    sTime = "0" + sTime;

    // Fix minutes.
    if (sTime.substr(4, 1) == ":")
    sTime = sTime.substr(0, 3) + "0" + sTime.substr(3, 1) + sTime.substr(4, 2);

    // Fix seconds.
    var lenght = 0;
    for (var i in sTime)
    lenght++;

    if (lenght < 8)
    sTime = sTime.substr(0, 6) + "0" + sTime.substr(6, 1);

    //Set variables
    hours = sTime.substr(0,2);
    minutes = sTime.substr(3,2);
    seconds = sTime.substr(6,2);
    }

    function getTime()
    {
    //Get time
    fixTime();

    //Set time diffrence
    hours = parseInt(hours) + 6;
    if (hours >= 24)
    hours = "0" + (hours - 24);

    //Set as string
    sTime = hours + ":" + minutes + ":" + seconds;

    //Write time
    document.getElementById("clock").innerHTML = sTime;

    //Wait 1 second
    setTimeout("TimeCount()", 1000);
    }

    function TimeCount()
    {
    //Seconds + 1
    seconds = parseInt(seconds) + 1;

    //Check for overtimes
    if (seconds == 60)
    {
    seconds = 0;
    minutes = parseInt(minutes) + 1;
    if (minutes == 60)
    {
    minutes = 0;
    hours = hours + 1;
    if (hours == 24)
    hours = 0;
    }
    }

    //Set new sTime
    sTime = hours + ":" + minutes + ":" + seconds;

    //Fix times
    fixTime(sTime);

    //Write time
    document.getElementById("clock").innerHTML = sTime;

    //Wait 1 second
    setTimeout("TimeCount()", 1000);
    }
    </script>

    This is the javascript I use.. body onload="getTime()"
    Now maybe this is written badly, if you know any better ways, show me!

    What I want is the SERVER time,, so not pc time.. So I get it from a php code, then I want it to count without refreshing the whole webpage.

    I need a 24 hour clock.. the problems I'm facing now are in IE with having a hour count, and in FF and Chrome it counts from 08 seconds to 01 seconds in a loop without counting the minutes.

    So it has a lot of problems. Could you guys help me to write 1 script that is using for these 3 browsers, without any problems?

    Ps. my server is located in the US, I'm from The Netherlands, so time diffrence of 6 hours...

  2. #2
    Join Date
    Oct 2007
    Location
    Western Massachusetts, USA
    Posts
    387
    I just coded this for you from scratch:
    PHP Code:
    <html>
    <head>
    <script language="javascript" type="text/javascript">

    <?php
    $d 
    getdate();
    echo 
    "var diff = new Date().getTime() - new Date(".$d['year'].", ".$d['mon'].", ".$d['mday'].", ".$d['hours'].", ".$d['minutes'].", ".$d['seconds'].", 0).getTime();\n";
    ?>

    function zeropad(n,str) {
    var prefix = "";
    str = ""+str;
      for (i = 0; i < n-str.length; i++) { prefix += "0"; }
    return prefix+str;
    }

    function setTime() {
    var ele = document.getElementById("servertime");
      if (ele) {
      var ltime = new Date();
      ltime.setTime(ltime.getTime()+diff);
      ele.innerHTML = zeropad(2,ltime.getHours())+":"+zeropad(2,ltime.getMinutes())+":"+zeropad(2,ltime.getSeconds());
      }
    }

    </script>
    </head>
    <body>

    <p>The current server time is <span id="servertime">[loading]</span>.</p>

    <input type="button" value="start clock" onclick="setInterval('setTime()',1000)">

    </body>
    </html>
    Note: this was not tested on a separate server than my own computer, so diff was minimal, making no real effect. I have to assume that it will offset correctly.
    Computer programmer / web developer.

  3. #3
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    Gathering a ready padded time string is as simple as ...

    Code:
    x = new Date().toGMTString().slice(16,25); // returns a string like 01:23:45

  4. #4
    Join Date
    Oct 2011
    Posts
    11
    Quote Originally Posted by JunkMale View Post
    Gathering a ready padded time string is as simple as ...

    Code:
    x = new Date().toGMTString().slice(16,25); // returns a string like 01:23:45
    If you could use it in my script,, then please help me by rewriting it..
    I'm pretty new to all this.. :P

  5. #5
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,268
    It's not so simple with server and local times... Even for the developers of the site (in central European summer time zone, JunkMale wrote Today at 10:22 AM after Savvykms which wrote Today at 12:05 AM ???)

    Numeric representation of months are different in javascript and PHP and furthermore (not to mention the daylight saving times) the Times difference must be reversed...

    Then the difference is given by :
    Code:
    echo "var diff = new Date(".$d['year'].", ".($d['mon']-1).", ".$d['mday'].", ".$d['hours'].", ".$d['minutes'].", ".$d['seconds'].", 0).getTime() - new Date().getTime();\n";
    After this changes, a difference less than 6 hours (time zone difference with Atlanta, Georgia, US - Eastern Daylight Time) suggests that the server or the local machine aren't on time (8 seconds) but (with or without milliseconds) gives no indication of the transmission time...

    The way is probably to work with UTC time (and toUTCString() witch is not depreciated) !

    EDIT : How can I wrote at 04:22 PM ???
    Last edited by 007Julien; 10-23-2011 at 10:00 AM. Reason: complement

  6. #6
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    Quote Originally Posted by 007Julien View Post
    It's not so simple with server and local times... Even for the developers of the site (in central European summer time zone, JunkMale wrote Today at 10:22 AM after Savvykms which wrote Today at 12:05 AM ???)

    Numeric representation of months are different in javascript and PHP and furthermore (not to mention the daylight saving times) the Times difference must be reversed...

    Then the difference is given by :
    Code:
    echo "var diff = new Date(".$d['year'].", ".($d['mon']-1).", ".$d['mday'].", ".$d['hours'].", ".$d['minutes'].", ".$d['seconds'].", 0).getTime() - new Date().getTime();\n";
    After this changes, a difference less than 6 hours (time zone difference with Atlanta, Georgia, US - Eastern Daylight Time) suggests that the server or the local machine aren't on time (8 seconds) but (with or without milliseconds) gives no indication of the transmission time...

    EDIT : How can I wrote at 04:22 PM ???
    YOU DO NOT ACCOUNT FOR DAY LIGHT SAVINGS.... This is something done on the local users machine. As soon as you start messing about with calculations on time deferences, you will find your code is introducing an additional 1 hour or missing an extra hour. If you use UTC time, this overcomes the problem. GMT is the standard by which ALL clocks in the world are set, even in the USA.

    Besides, a call to Microsoft technical help desk several years ago resolved this little chestnut.

    Getting the server time isn't as difficult as people are making out and you don't even need to use PHP at all to achieve this goal. One word... AJAX.

    A simple header request will return a header with a server time stamp which should be a UTC time stamp even though most will return GMT as in the same time as UTC time which when your in day light savings will be adrift by 1 hour which means a simple GMT & UTC time check will let you know if DLS are in effect on the local machine as not all countries observe DLS.

    The easiest document to get a header from via ajax is the current document.location which you get the response header for the "Date" and you will be returned a string which will look like Tuesday, 31 February 2011 09:06:27 GMT and extracting the raw information would be as simple as issuing a "split" at spaces, pop the last two elements off and keep the result of the 2nd "pop" or slice it out by finding the last space in the string and chopping it 8 character prior to the last space in the string would grab the time.

    Either way, you will have to do some coding. The AJAX method IMHO is a good system for servers and websites with no access to things like server sides.

    Also.... STOP USING setTimeout, its setInterval for all timing events that repeat at a set interval, like clocks...It only needs setting once and it will run for the duration the browser window is open... Therefore setTimeout("TimeCount()", 1000); can be deleted from the function and a clock = setInterval("TimeCount()",1000) placed outside that function will call that function every second until it is killed with a clearInterval(clock) call on the object that its bound to.
    Last edited by JunkMale; 10-23-2011 at 10:19 AM.

  7. #7
    Join Date
    Oct 2011
    Posts
    11

    Post New Script With 1 Problem

    I´ve written a new script (easier to understand for me):

    <script type="text/javascript">
    //Get time in Js
    var sTime = "<?php echo date("H:i:s"); ?>";

    //Set values
    var hours = sTime.substr(0, 2);
    var minutes = sTime.substr(3, 2);
    var seconds = sTime.substr(6, 2);

    //Set value for hours
    hours = parseInt(hours, 10);

    //Set time diffrence
    hours = hours + 6;

    //Check for overtime
    if (hours == 24)
    {
    hours = "00";
    sTime = hours + ":" + minutes + ":" + seconds;
    }

    else if (hours > 24)
    {
    //Count 24 back
    hours = hours - 24;

    //Set new sTime string
    sTime = "0" + hours + ":" + minutes + ":" + seconds;
    }

    else
    sTime = hours + ":" + minutes + ":" + seconds;

    //Start Counter
    setInterval("Count()", 1000);

    function getTime()
    {
    document.getElementById("clock").innerHTML = sTime;
    }

    function Count()
    {
    //Set values
    hours = sTime.substr(0, 2);
    minutes = sTime.substr(3, 2);
    seconds = sTime.substr(6, 2);

    //Clear all zero's & strings
    hours = parseInt(hours, 10);
    minutes = parseInt(minutes, 10);
    seconds = parseInt(seconds, 10);

    //Count + 1 second
    seconds = seconds + 1;

    //Check for overtime
    if (seconds == 60)
    {
    seconds = 0;
    minutes = minutes + 1;
    if (minutes==60)
    {
    minutes = 0;
    hours = hours + 1;
    if (hours == 24)
    hours = 0;
    }
    }

    //Set new sTime string
    sTime = hours + ":" + minutes + ":" + seconds;

    // Fix hours
    if (sTime.substr(1, 1) == ":")
    sTime = "0" + sTime;

    // Fix minutes & seconds
    if (sTime.substr(4, 1) == ":")
    {
    if (seconds > 10)
    sTime = sTime.substr(0, 3) + "0" + sTime.substr(3, 4);
    else
    sTime = sTime.substr(0, 3) + "0" + sTime.substr(3, 2) + "0" + sTime.substr(5, 1);
    }

    //Fix seconds
    else if (seconds < 10)
    sTime = sTime.substr(0, 6) + "0" + sTime.substr(6, 1);

    //Write sTime
    document.getElementById("clock").innerHTML = sTime;
    }
    </script>
    I only use it to display, it won't be affecting any other things.
    I want a 24 hour clock.
    The script I got now, has 1 problem, when it counts + 1 hour, the seconds loop from 01 to 09...

    I know that the browser speed is infecting the time, the servertime displayed is actually slowed by the loading time of the whole document and the runtime of the script..

    For now, I would like to have a script which is running on client..
    It doesn't have to be that professional! Maybe I'll update it later by retrieving the time from time.microsoft.com every second...

    Could you help me fix this one problem I got at the moment?

  8. #8
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    A very simple clock I wrote the other day that is in just the format you want...

    HTML Code:
    <!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>Untitled Document</title>
    </head>
    
    <body><div id="clock"><script>
    clock = {
    	cycles:0,
    	update:function(){
    		clock.currentTime = new Date().toGMTString(); // outputs 00:00 format hh:mm
    		clock.obj.innerText = clock.currentTime.slice(16,25) + " Hrs"; // update with the string
    	},
    	init:function(){
    		if( ++clock.cycles > 99 || clock.obj ) clearInterval( clock.auto );
    		if( !clock.obj ){ 
    			try{ clock.obj = document.getElementById("clock"); }catch(e){ delete e; }
    			}
    		if( clock.obj ){ // if we have the object, set an interval timer to run
    			clock.auto = setInterval("clock.update()",1000);
    			clock.obj.title = "Clock";
    			}
    	},
    	auto:setInterval("clock.init()",1000)
    }
    </script></div>
    </body>
    </html>
    This is JSON method of coding javascript. Its an object that hods data and functions and as illustrated can be auto run using event timers.

    The method I chose is to strip out a time from a timestring, you may want to consider the UTC method as its time is universal and is not subject to the problems of the DSL issues that the local machine has.

    The question now is how you want to implement this for a server time...
    Last edited by JunkMale; 10-23-2011 at 01:28 PM.

  9. #9
    Join Date
    Oct 2011
    Posts
    11
    Mhm..
    This ia NOT with seconds :$

    Thnx for your help anyways, I learn stuff by reading codes which are possible.. :P
    I actually just want the server time, not any GMT or UTC time, because who knows if the server is at any of these times exactly :P

    Well, it isn't a real problem, but I jsut want it like my way, only want it working.. and maybe written better. I am still a noob to the most, I use this for a project I started myself, and luckely I can also use it for school.. it doesn't have to be perfect, just wanna learn from it..

    So uhm, my way, but with the problem fixed oke ? :$
    Thnx for the help anyways, I would have never thought about using GTM or UTC xD

    Edit:
    Why do you slice with 16 & 25?
    What do this numbers do? What does slice do?
    Last edited by FireVirus; 10-23-2011 at 02:28 PM. Reason: Little question on slice

  10. #10
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    Your missing the point.

    You use the toGMT or toUTC method based on the date you initalize from the server.

    All your taking from those methods is a slice out of a string thats ready prepped for display and no need to "pad" as the item is ready padded.

    All you have to do is implement the "Server" aspect of this which can either be done via PHP or via an AJAX header call for the Date which itself will be a GMT or UTC formatted string too. The server time will be a GMT time as well, so no matter what you do, your not getting away with avoiding GMT or UTC.

    Sorry

    Slice....

    as the term implies, it slices a part of a string, all strings are or can also be seen as an array where 0 is the first character, 1 is the second character and so on, so a string and slicing from character 16 to character 25 in the string returned from the use of toGMTString() slices out a string of characters like 09:06:27
    Last edited by JunkMale; 10-23-2011 at 03:20 PM.

  11. #11
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,268
    I do not know who miss the point ? I thought the question was : How to display the server local time ? Isn't it ?

    The date() or getdate() functions give a local time with PHP !

    I do not forgot the daylight saving times even if they are not useful (for Atlanta and Paris) at this time !
    Last edited by 007Julien; 10-23-2011 at 03:55 PM.

  12. #12
    Join Date
    Oct 2011
    Posts
    11
    I know hot it works with 0 = 1st char etc..
    Just didn;t thought about the other information you get,, so I wondered why you started with 16 :$..
    Thnx :P

    I don;t wanna avoid that, but what you're trying to say is that I can ask for the time from the server every second by using this method? (in AJAX..)
    Cause I would like that, because now the browsers calculation speed, and loading speed,, is affecting the timer..

    @ Julien,, do you mean summertime etc?
    In that case, I will make my whole script the way it is decided by the server time, I may assume that the host will have this time updated automaticly to the right time of the year :P Oké, there wil lstill be a diffrence in time when changing the hour, but when I've finished my project, I will hire an Dutch server, so that wouldn't be a problem at all..

  13. #13
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    so....

    To do this the PHP way, forget making a script like prviously shown, in your .php page,
    Code:
    servertimeObject = new Date(<?php echo "'".date("r")."'"; ?>); // server time
    alert ( servertimeObject.toGMTString() );
    Passing the RFC formatted date as a string to the Javascript date object will recognize the format.

    So with that information obtained, you can calculate the time difference and create a date/time object that you can harvest the GMTString that you slice the time out of.

    Looking at this post, you should have all the information you need to create your function to get the time from the server directly. If you go for the Ajax method, it returns an RFC time stamp that looks like Sun, 23 Oct 2011 21:42:42 +0100 and the w3 spec states
    The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822. The field value is an HTTP-date, as described in section 3.3.1; it MUST be sent in RFC 1123 [8]-date format.
    Date = "Date" ":" HTTP-date

    An example is
    Date: Tue, 15 Nov 1994 08:12:31 GMT

    Origin servers MUST include a Date header field in all responses, except in these cases:
    1. If the response status code is 100 (Continue) or 101 (Switching
    Protocols), the response MAY include a Date header field, at
    the server's option.
    2. If the response status code conveys a server error, e.g. 500
    (Internal Server Error) or 503 (Service Unavailable), and it is
    inconvenient or impossible to generate a valid Date.
    3. If the server does not have a clock that can provide a
    reasonable approximation of the current time, its responses
    MUST NOT include a Date header field. In this case, the rules
    in section 14.18.1 MUST be followed.
    so using the Ajax method will return an RFC date that the javascript Date() object should understand.

  14. #14
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    Give this a whirl, I can not tell if its the server time correctly because my web hosting company placed the server I use about half a mile down the road... So this would need to be tested on a server elsewhere.

    HTML Code:
    <!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>Untitled Document</title>
    </head>
    
    <body><div id="clock"><script>/*
    Website clock that displays the server time on the local users machine. Requires PHP to set the time string to RFC 2822 format.
    
    Script as seen on Webdeveloper.com is supplied as is without warranty, etc, so your on your todd. Please tell a friend.
    
    */
    difference = new Date("<?php echo date('r'); ?>") - new Date().getTime(); // get the time difference
    clock = {
    	cycles:0,
    	update:function(){
    		servertimeObject = new Date( (new Date().toGMTString()) ).getTime() + difference;
    		clock.currentTime = new Date( servertimeObject ).toGMTString(); // outputs format hh:mm:ss
    		clock.obj.innerText = clock.currentTime.slice(16,25) + " Hrs"; // update with the string
    	},
    	init:function(){
    		if( ++clock.cycles > 99 || clock.obj ) clearInterval( clock.auto );
    		if( !clock.obj ){ 
    			try{ clock.obj = document.getElementById("clock"); }catch(e){ delete e; }
    			}
    		if( clock.obj ){ // if we have the object, set an interval timer to run
    			clock.auto = setInterval("clock.update()",1000);
    			clock.obj.title = "Clock";
    			}
    	},
    	auto:setInterval("clock.init()",1000)
    }
    </script></div>
    </body>
    </html>
    Last edited by JunkMale; 10-23-2011 at 04:18 PM.

  15. #15
    Join Date
    Oct 2011
    Posts
    11

    hmm

    Like I said, I'm a total noob..
    I don't know any about AJAX :$..

    As well,, I don;t know anything about RFC, or using objects :$..
    But ok, I tried your code in IE, Firefox & Google Chrome,, it ONLY works in IE.. and yeas, it works! (Couldn't find any errors with IE error detection, and it works..)

    Maybe I'll make use of it, and test if it can be also done with FF and Chrome..
    But let's prepare for the NO, it won't work in FF & Chrome..
    Then I should use AJAX? I would rather use PHP & JS only then.. :P

    So in that case, IS it possible to do it some way I tried to? It has 2 errors I detected.. after + 1 hour, it loops the seconds from 01 to 09.. as well for when it runs at 09 minutes,, it loops the seconds from 01 to 09, without changing anything else.. it gets "stuck" for like hours..

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