473,387 Members | 1,483 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Live Server Clock

TheServant
1,168 Expert 1GB
Hey guys,
I used this free tutorial on how to make a live server clock. I did, but a) doesn't work (not too worried, I am sure I can fix this) and b) it out puts the clock to a input text field?!

I want it to be in just a normal text display?

The core code:
Expand|Select|Wrap|Line Numbers
  1. <!--
  2. function startclock()
  3. {
  4. var server_time = new Date();
  5. var server_hours = server_time.getHours();
  6. var server_mins = server_time.getMinutes();
  7. var server_secs = server_time.getSeconds();
  8.  
  9. if (server_mins < 10)
  10. server_mins = "0" + server_mins;
  11. if (server_secs < 10)
  12. server_secs = "0" + server_secs;
  13.  
  14. document.live_time_form.live_time_clock.value=server_hours+":"+server_mins+":"+server_secs
  15.  
  16. setTimeout('startclock()',1000);
  17.  
  18. }
  19. //-->
What I put in my page:
Expand|Select|Wrap|Line Numbers
  1. <head>
  2. ...
  3. <script type="text/javascript" src="../main/scripts/live_time.js"></script> 
  4. ...
Expand|Select|Wrap|Line Numbers
  1. ...<body onLoad="startclock()">...
Expand|Select|Wrap|Line Numbers
  1. ...<form name="live_time_form">
  2. Server Time: <INPUT TYPE="text" name="live_time_clock" size="15">
  3. </form>...
So I want to replace the document.live_time_form.live_time_clock.value line, and also my <form> to some simple <p> or something?
Thanks for your help!
Feb 12 '08 #1
24 8508
hirak1984
316 100+
...<form name="live_time_form">
Server Time: <INPUT TYPE="text" name="live_time_clock" size="15">
</form>...
instead try using

a span or a div with the same name (="live_time_clock")
it should work
Feb 12 '08 #2
acoder
16,027 Expert Mod 8TB
So I want to replace the document.live_time_form.live_time_clock.value line, and also my <form> to some simple <p> or something?
Replace the form with a div/span/p/other element with id "live_time_clock" and then replace line4 with:
Expand|Select|Wrap|Line Numbers
  1. document.getElementById("live_time_clock").innerHTML = server_hours+":"+server_mins+":"+server_secs;
Feb 13 '08 #3
acoder
16,027 Expert Mod 8TB
instead try using

a span or a div with the same name (="live_time_clock")
it should work
You're along the right lines, but adiv/span doesn't have a value attribute, so you'd need to use innerHTML or the DOM methods.
Feb 13 '08 #4
TheServant
1,168 Expert 1GB
Sounds good, but I think I'm missing something:

Added your document.getElementById suggestion, and that makes sense.
I changed the <form> section to:
[HTML]<span id="line_time_clock">&nbsp;</span>[/HTML], which didn't work, and then tried without the &nbsp; along with <p> and <div>. All of these produce no output? What should go between <span> and </span>? I think that's where the problem is?

Also, I want to display the server time rather than the user's PC time, so I just had this in the code instead of the plain js date() function:
[PHP]var server_time = new Date("<?php $time = date('F d, Y H:i:s'); echo($time); ?>");[/PHP]
Does this look right?
Feb 13 '08 #5
acoder
16,027 Expert Mod 8TB
"line_time_clock" should be "live_time_clock".
Feb 13 '08 #6
TheServant
1,168 Expert 1GB
lol, argh, typo! It's late, and I should be going to bed! But I really wana get this working! It still is not giving any out put with that:

[HTML]<script type="text/javascript"><!--
function startclock()
{
var server_time = new Date();
var server_hours = server_time.getHours();
var server_mins = server_time.getMinutes();
var server_secs = server_time.getSeconds();

if (server_mins < 10)
server_mins = "0" + server_mins;
if (server_secs < 10)
server_secs = "0" + server_secs;

document.live_time_form.live_time_clock.value=serv er_hours+":"+server_mins+":"+server_secs;

setTimeout('startclock()',1000);

}
//--></script>[/HTML]

[HTML]Server Time: <span id="live_time_clock">&nbsp;</span>[/HTML]
Feb 13 '08 #7
acoder
16,027 Expert Mod 8TB
Chang line 14 in the JavaScript to:
Expand|Select|Wrap|Line Numbers
  1. document.getElementById("live_time_clock").innerHTML=server_hours+":"+server_mins+":"+server_secs;
Feb 13 '08 #8
TheServant
1,168 Expert 1GB
Chang line 14 in the JavaScript to:
Expand|Select|Wrap|Line Numbers
  1. document.getElementById("live_time_clock").innerHTML=server_hours+":"+server_mins+":"+server_secs;
Damn it, that was the old code. I have already changed that, but changed it back to test it. So line 14 changed still does not solve the problem, can anyone see anything else?
Feb 13 '08 #9
markrawlingson
346 Expert 100+
What exactly is the problem with it at this point? If it's throwing an error please let us know what it is. If it's not throwing an error, but the time is just not moving.. it's probably because of this.

Expand|Select|Wrap|Line Numbers
  1. [color=#000000]var[/color] server_time = [color=#000000]new[/color] [color=#000066]Date[/color][color=#66cc66]([/color][color=#ff0000]"<?php $time = date('F d, Y H:i:s'); echo($time); ?>"[/color][color=#66cc66])[/color];
  2.  
That value won't get updated unless you refresh the page, and that defeats the purpose.

and by the way, you don't need to put anything between the <span></span> tags, the innerHTML section of the script does that for you.

I'll whip up something for you tonight.

Sincerely,
Mark

Damn it, that was the old code. I have already changed that, but changed it back to test it. So line 14 changed still does not solve the problem, can anyone see anything else?
Feb 14 '08 #10
TheServant
1,168 Expert 1GB
Thanks for all your help guys. I have a code that works, I haven't put it up yet, but now my only problem is the Javascript date() function...

So basically I want my server time, not the client time. I have tried a lot of different formats, but I can't get it, nor find exactly what I need.
I have:
Expand|Select|Wrap|Line Numbers
  1. new Date("<?php $time = date('F d, Y H:i:s'); echo($time); ?>")
Which gives something like:
Expand|Select|Wrap|Line Numbers
  1. new Date(February 14, 2008 11:15:45)
But this doesn't seem to do anything, which means that my php input to the javascript function Date() is wrong?
Feb 14 '08 #11
my php input to the javascript function Date() is wrong?
Correct! Valid constructors for date are:

Expand|Select|Wrap|Line Numbers
  1. new Date();  // right now
  2. new Date(milliseconds) // # of milliseconds since 01/01/70 00:00:00
  3. new Date(dateString) // a string that represents the date in a format that is recognized by the Date.parse method
  4. new Date(yr_num, mo_num, day_num [, hr_num, min_num, sec_num, ms_num])
  5.  
You can probably put what you have in quotes to make it work:
Expand|Select|Wrap|Line Numbers
  1. new Date("February 14, 2008 11:15:45")
But if that fails -- and believe you me, the parse function fails miserably, try getting it in the format of:
Expand|Select|Wrap|Line Numbers
  1. new Date( "2008", "01", "14", "11", "15", "45")
.... oh, and note the month 0 = jan.


On a side note - everyone is recommending innerHTML?!? What's wrong with the world! You can use dom manipulation and not endorse the evil innerHTML tag :
Expand|Select|Wrap|Line Numbers
  1. var e = document.getElementById('live_time_clock');
  2. e.replaceChild( document.createTextNode( server_hours+":"+server_mins+":"+server_secs ), e.firstChild )
  3.  
[html]
<span id="live_time_clock">&nbsp;</span>
<!-- note the &nbsp; -- required for "firstChild" on first run -->
[/html]
Feb 14 '08 #12
TheServant
1,168 Expert 1GB
Thanks.
So u reckon I should change from innerHTML? Haven't used the child function, what's the advantage? I changed my php format but it's still not working.
This is what the function looks like once PHP has done it's thing:
Expand|Select|Wrap|Line Numbers
  1. new Date("2008, 02, 14,  11, 40, 54");
(I do not have milli-seconds as that is only available on php 5.25 or something which is above my version).

The output string on the page is "NaN:NaN:NaN"???

PS - without the php, it works fine, so it's only my php now!
Feb 14 '08 #13
So u reckon I should change from innerHTML? Haven't used the child function, what's the advantage?
I do reckon... not sure if there's any advantage. Actually when dealing with huge amounts of data, innerHTML is faster.... The only real advantage comes when you need to reuse the elements from around different javascript functions -- you just need to declare it once and manipulate, instead of doing a 'getElementById(_id).innerHTML = "" to change..... oh, that and you avoid using a proprietary html property.... and when people look at your code they'll be like "wooow this guy really knows his stuff"

I changed my php format but it's still not working.
This is what the function looks like once PHP has done it's thing:
Expand|Select|Wrap|Line Numbers
  1. new Date("2008, 02, 14,  11, 40, 54");
(I do not have milli-seconds as that is only available on php 5.25 or something which is above my version).
Getting closer.... analyze this:

Expand|Select|Wrap|Line Numbers
  1. alert( new Date( "2008", "01", "14", "11", "15", "45") )
  2. alert( new Date("February 14, 2008 11:15:45") )
  3.  
Both return the same thing.... I would recommend the first because you never know whether the parse function will crap out on ... oh i don't know .. single-digit minutes or something. it's super-shoddy in my experience.
Feb 14 '08 #14
markrawlingson
346 Expert 100+
If you want to get the SERVER time rather than the CLIENT time then you don't need to use the date() call in javascript at all. In fact, if you do it the way you're doing it right now you'll only ever get the same time, it won't count. Why you ask? Because when the page loads, your PHP date function is echoing the current server time to your javascript date function - that "current time" is the time when the page loads. That essentially means that unless you refresh the page so the PHP code can re-execute (and therefore echo the new current server time to your javascript date() function), your javascript will ALWAYS have the same date, thus - it won't count.

If you want to grab the server time you'll need to use AJAX to call a PHP script in the background which simply has the date function. This way, you are constantly calling on the server to hand you the new time.

Name the .php page 'getTime.php' (or if you name it something different you'll have to change the references to it in the js.) The php file itself is even simpler than you already have.

Expand|Select|Wrap|Line Numbers
  1. <?php echo date('F d, Y H:i:s') ?>
  2.  
(that's it.)

and the actual page...

Expand|Select|Wrap|Line Numbers
  1. <html>
  2.  <head>
  3.   <script language="javascript">
  4.    <!--
  5.     function doAjaxGet(dataSource) {
  6.        if(navigator.appName == "Microsoft Internet Explorer") {
  7.          objHTTP = new ActiveXObject("Microsoft.XMLHTTP");
  8.        } else {
  9.          objHTTP = new XMLHttpRequest();
  10.        }
  11.        objHTTP.open("POST", dataSource, true);
  12.        objHTTP.onreadystatechange = function() 
  13.        { 
  14.        if (objHTTP.readyState == 4 && objHTTP.status == 200) {
  15.            document.getElementById('oClock').innerHTML = objHTTP.responseText;
  16.          }
  17.        }
  18.          objHTTP.send('null'); 
  19.        }
  20.     function startclock() {
  21.      doAjaxGet('getTime.php');
  22.       setTimeout('startclock()',1000);
  23.      }
  24.    //-->
  25.   </script>
  26.  </head>
  27.  <body onLoad="startclock();">
  28.   <div id="oClock"></div>
  29.  </body>
  30. </html>
  31.  
Sincerely,
Mark
Feb 14 '08 #15
TheServant
1,168 Expert 1GB
Expand|Select|Wrap|Line Numbers
  1. alert( new Date( "2008", "01", "14", "11", "15", "45") )
  2. alert( new Date("February 14, 2008 11:15:45") )
  3.  
So I need something like:
[HTML]new Date("<?php
$y=date('Y');
$m=date('m') - 1;
$d=date('d');
$H=date('H');
$i=date('i');
$s=date('s');
echo($y.'/"'.$m.'/"'.$d.'/"'.$H.'/"'.$i.'/"'.$s);
?>"); [/HTML]

*EDIT* Awsome Mark, I will give both of these a go and let you all know how it turns out when I get home (~5hrs). One question Mark, if you are constantly asking for an updated server time, will this not take up a whole lotta memory or something calling from the server every second?
Feb 14 '08 #16
markrawlingson
346 Expert 100+
It certainly *can* - but you have to look at what you're asking the server to do, which in this case is just asking it to echo 1 line of code - the time - not exactly what you'd call a resource hog. The only way you'd have any problems is if you had a few thousands users logged on at the same time watching this thing count, in that case you're sending x thousand server requests a second :P They're small server requests but you get my point.. it can add up.

Is it the most efficient way? Nope! But it's the simplest and most straight forward way. If you want the most effecient, you'd have to basically return the server time with PHP to a javascript variable once, and then write a fairly complicated set of javascript functions to count the seconds until they reach 60, then set that variable back to 0 and increment a minute variable by 1. Then when the minute variable = 60, incremement the hour, and when the hour variable reaches 24 , switch the day, then you'd have to determine the month to keep track of when the month should switch (after day variable = 28, 30, or 31?) - and then you'd have to track the years, and then you'd even have to track leap years.

Essentially you'd have to write a whole date and time handler and base it's initial date off of the server time. This is much easier i think you can agree lol

Sincerely,
Mark

So I need something like:
[HTML]new Date("<?php
$y=date('Y');
$m=date('m') - 1;
$d=date('d');
$H=date('H');
$i=date('i');
$s=date('s');
echo($y.'/"'.$m.'/"'.$d.'/"'.$H.'/"'.$i.'/"'.$s);
?>"); [/HTML]

*EDIT* Awsome Mark, I will give both of these a go and let you all know how it turns out when I get home (~5hrs). One question Mark, if you are constantly asking for an updated server time, will this not take up a whole lotta memory or something calling from the server every second?
Feb 14 '08 #17
TheServant
1,168 Expert 1GB
I see your point. Well seeing as I only want the time (not date), I might play around with javascript to see what i can do. I need the practice as I have hardly used javascript besides altering already made scripts.

Oh and does anyone know what the NaN:NaN:NaN means? It is my current output when I tell it to write: Hours:Mins:Secs
Feb 14 '08 #18
Oh and does anyone know what the NaN:NaN:NaN means? It is my current output when I tell it to write: Hours:Mins:Secs
NaN means: Not a Number -- generally raised if you divide by zero or square route of -1, things like that.... in this case, if you forgot () on the function calls, that would do it.... or if the date is invalid, that woluld do it.... try and alert( server_time ) -- if it returns "Invalid Date", there's your problem.

Mark raises some very good points... but, it's really not all that complicated to use the build in javascript date object -- granted, you do need to give it a constructor which includes yyyy/mm/dd, which you may not be interested in, buuuut, you can increment the seconds with a single line of code... .try this out -- replace Date constructor with your own brand:

Expand|Select|Wrap|Line Numbers
  1. var timeclock, server_time;
  2.  
  3. function init() {
  4.   timeclock = document.getElementById('live_time_clock');
  5.   if( timeclock.childNodes.length == 0 ) timeclock.appendChild( document.createTextNode("&nbsp;") );
  6.   server_time = new Date("2005", "1", "12", "12", "50", "45" )
  7.   incrementClock();
  8. }
  9.  
  10.  
  11. function incrementClock()  {
  12.   server_time.setSeconds( server_time.getSeconds() + 1 );
  13.   timeclock.replaceChild( document.createTextNode( (server_time.getHours() < 10 ? "0" + server_time.getHours() : server_time.getHours()) + ":" + (server_time.getMinutes() < 10 ? "0" + server_time.getMinutes() : server_time.getMinutes()) + ":" + (server_time.getSeconds() < 10 ? "0" + server_time.getSeconds() : server_time.getSeconds()) ), timeclock.firstChild );
  14.   setTimeout( "incrementClock();", 1000);
  15. }
  16.  
[html]
<body onLoad="init();">
<div id="live_time_clock"></div>
</body>
[/html]
of course it's not perfect -- the code, in theory, takes some time to run so after each 1000 milliseconds, your time is behind by however long it takes to increment the clock & pop it to the screen.... after a while of idling on the page, it may run itself off..... the up-side to the client-side incremntation is you're not going back to the server every second to grab a few bytes of data.

also, may want to write a "padZero" function -- incredibly handy in the long run for those pesky leading zeros.
Feb 14 '08 #19
acoder
16,027 Expert Mod 8TB
On a side note - everyone is recommending innerHTML?!? What's wrong with the world! You can use dom manipulation and not endorse the evil innerHTML tag :
Expand|Select|Wrap|Line Numbers
  1. var e = document.getElementById('live_time_clock');
  2. e.replaceChild( document.createTextNode( server_hours+":"+server_mins+":"+server_secs ), e.firstChild )
  3.  
[html]
<span id="live_time_clock">&nbsp;</span>
<!-- note the &nbsp; -- required for "firstChild" on first run -->
[/html]
True, innerHTML is non-standard, but it's supported by practically all browsers. It's fast, quick and easy, though there's nothing wrong with using the DOM methods.
Feb 14 '08 #20
acoder
16,027 Expert Mod 8TB
If I'm following correctly, you want to display the clock and update every few milliseconds/every second. How about using PHP to generate JavaScript with the date/time, e.g.
[php]echo "var hour = ".$hour.";";
// and so on...[/php] and then use the JavaScript Date() object's set*** methods to set the date/time. Then, use tswaters' incrementClock() function to update the time. If you want accuracy, every minute or so, you could make an Ajax request to update from the server again.
Feb 14 '08 #21
TheServant
1,168 Expert 1GB
It works! tswaters' code with a few tweeks like acoder suggested and I have it! tswater, you should include this on you're site or something, I am sure a lot of people would like code like this!

One question though. I have the file as a .php even though it's 90% js. Is there a way to include php in a .js file?
Feb 14 '08 #22
acoder
16,027 Expert Mod 8TB
One question though. I have the file as a .php even though it's 90% js. Is there a way to include php in a .js file?
No, that's not possible. JavaScript is client-side and PHP is server-side. Why would it be a problem if it's 90% JavaScript? The browser sees HTML/JavaScript anyway.
Feb 14 '08 #23
TheServant
1,168 Expert 1GB
No, that's not possible. JavaScript is client-side and PHP is server-side. Why would it be a problem if it's 90% JavaScript? The browser sees HTML/JavaScript anyway.
Just looks a bit messy, but all good! acoder, tswaters, markrawlingson and hirak1984, you all rock! Thanks for you help, really appreciate it! This was one of those things which I really wanted to do but simply didn't know enough, so thanks again.

This can be closed.
Feb 14 '08 #24
acoder
16,027 Expert Mod 8TB
You're welcome. Glad it's all working.
Feb 15 '08 #25

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Steven | last post by:
I actually have two questions: 1. I try to get current time, but the time I got is 1 hour different from my local time. I assume it is caused by Time Zone. So is there any easy way to fix this?...
5
by: Thomas Brathans | last post by:
Hi, when I try to execute the obove mentioned to synchronise the servertime by a php-script, it doesn't work. Other shell-commands work fine. Executing ntpdate <server> directly in the shell...
7
by: Dave Smithz | last post by:
Hi There, I have taken over someone else's PHP code and am quite new to PHP. I made some changes and have implemented them to a live environment fine so far. However, I now want to setup a...
3
by: James Harriman | last post by:
Hi, I need to be able to measure a time interval in milliseconds on a windows machine. I have tried using time.clock() but it appears to measure time in seconds...Is there a way to measure time...
15
by: Michael Rybak | last post by:
hi, everyone. I'm writing a 2-players game that should support network mode. I'm now testing it on 1 PC since I don't have 2. I directly use sockets, and both client and server do...
22
by: Mr Newbie | last post by:
I was thinking about developing a workflow application yesterday and was musing over the different approaches than one could take in restricting specific actions on a ticket( Form ) at any said...
1
by: VB Programmer | last post by:
I want to display the Live time in New York and Hong Kong on my website. Any suggestions on how to display these live clocks? I suppose some client side scripting is necessary because I don't...
11
by: Krzysztof Retel | last post by:
Hi guys, I am struggling writing fast UDP server. It has to handle around 10000 UDP packets per second. I started building that with non blocking socket and threads. Unfortunately my approach...
1
by: Jean-Paul Calderone | last post by:
On Fri, 21 Nov 2008 00:20:49 -0200, Gabriel Genellina <gagsl-py2@yahoo.com.arwrote: If you want to try this program out on POSIX, make sure you change the time.clock() calls to time.time() calls...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.