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: - <!--
-
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=server_hours+":"+server_mins+":"+server_secs
-
-
setTimeout('startclock()',1000);
-
-
}
-
//-->
What I put in my page: - <head>
-
...
-
<script type="text/javascript" src="../main/scripts/live_time.js"></script>
-
...
- ...<body onLoad="startclock()">...
- ...<form name="live_time_form">
-
Server Time: <INPUT TYPE="text" name="live_time_clock" size="15">
-
</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!
24 8508
...<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
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: - document.getElementById("live_time_clock").innerHTML = server_hours+":"+server_mins+":"+server_secs;
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.
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"> </span>[/HTML], which didn't work, and then tried without the 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?
"line_time_clock" should be "live_time_clock".
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"> </span>[/HTML]
Chang line 14 in the JavaScript to: - document.getElementById("live_time_clock").innerHTML=server_hours+":"+server_mins+":"+server_secs;
Chang line 14 in the JavaScript to: - 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?
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. -
[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];
-
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?
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: - new Date("<?php $time = date('F d, Y H:i:s'); echo($time); ?>")
Which gives something like: - 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?
my php input to the javascript function Date() is wrong?
Correct! Valid constructors for date are: -
new Date(); // right now
-
new Date(milliseconds) // # of milliseconds since 01/01/70 00:00:00
-
new Date(dateString) // a string that represents the date in a format that is recognized by the Date.parse method
-
new Date(yr_num, mo_num, day_num [, hr_num, min_num, sec_num, ms_num])
-
You can probably put what you have in quotes to make it work: - 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: - 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 : -
var e = document.getElementById('live_time_clock');
-
e.replaceChild( document.createTextNode( server_hours+":"+server_mins+":"+server_secs ), e.firstChild )
-
[html]
<span id="live_time_clock"> </span>
<!-- note the -- required for "firstChild" on first run -->
[/html]
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: - 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!
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: - 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: -
alert( new Date( "2008", "01", "14", "11", "15", "45") )
-
alert( new Date("February 14, 2008 11:15:45") )
-
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.
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. -
<?php echo date('F d, Y H:i:s') ?>
-
(that's it.)
and the actual page... -
<html>
-
<head>
-
<script language="javascript">
-
<!--
-
function doAjaxGet(dataSource) {
-
if(navigator.appName == "Microsoft Internet Explorer") {
-
objHTTP = new ActiveXObject("Microsoft.XMLHTTP");
-
} else {
-
objHTTP = new XMLHttpRequest();
-
}
-
objHTTP.open("POST", dataSource, true);
-
objHTTP.onreadystatechange = function()
-
{
-
if (objHTTP.readyState == 4 && objHTTP.status == 200) {
-
document.getElementById('oClock').innerHTML = objHTTP.responseText;
-
}
-
}
-
objHTTP.send('null');
-
}
-
function startclock() {
-
doAjaxGet('getTime.php');
-
setTimeout('startclock()',1000);
-
}
-
//-->
-
</script>
-
</head>
-
<body onLoad="startclock();">
-
<div id="oClock"></div>
-
</body>
-
</html>
-
Sincerely,
Mark
-
alert( new Date( "2008", "01", "14", "11", "15", "45") )
-
alert( new Date("February 14, 2008 11:15:45") )
-
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?
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?
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
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: - var timeclock, server_time;
-
-
function init() {
-
timeclock = document.getElementById('live_time_clock');
-
if( timeclock.childNodes.length == 0 ) timeclock.appendChild( document.createTextNode(" ") );
-
server_time = new Date("2005", "1", "12", "12", "50", "45" )
-
incrementClock();
-
}
-
-
-
function incrementClock() {
-
server_time.setSeconds( server_time.getSeconds() + 1 );
-
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 );
-
setTimeout( "incrementClock();", 1000);
-
}
-
[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.
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 : -
var e = document.getElementById('live_time_clock');
-
e.replaceChild( document.createTextNode( server_hours+":"+server_mins+":"+server_secs ), e.firstChild )
-
[html]
<span id="live_time_clock"> </span>
<!-- note the -- 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.
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.
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?
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.
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.
You're welcome. Glad it's all working.
Sign in to post your reply or Sign up for a free account.
Similar topics
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?...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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$) {
}
...
|
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
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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,...
|
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...
|
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,...
| |