I try to display the current time in my server(the web page it's in my server) but when I open the web page I get the time on the puter that runs the page.
Is there a way to do that ?
This is my code :
function startTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m=checkTime(m);
s=checkTime(s);
$('#cTime').val(h+":"+m+":"+s);
t=setTimeout(function(){startTime()},500);
}
function checkTime(i){
if (i<10) {
i="0" + i;
}
return i;
}
Thank you.
I try to display the current time in my server(the web page it's in my server) but when I open the web page I get the time on the puter that runs the page.
Is there a way to do that ?
This is my code :
function startTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m=checkTime(m);
s=checkTime(s);
$('#cTime').val(h+":"+m+":"+s);
t=setTimeout(function(){startTime()},500);
}
function checkTime(i){
if (i<10) {
i="0" + i;
}
return i;
}
Thank you.
Share Improve this question asked Nov 23, 2012 at 16:46 MilsMils 3886 silver badges22 bronze badges 1- 1 Do you want just the time on the server or should it also be in the same timezone of the server? – Ja͢ck Commented Nov 23, 2012 at 16:52
5 Answers
Reset to default 4JavaScript will always return the time on the puter it's run on since it's executed client-side.
You can write a simple script on your server that outputs the current time and send a request to that script via JavaScript.
You can do something like this:
PHP
<?php
// get_time.php
// Simple!
echo time();
?>
JavaScript
// Using jQuery's GET function...
$.get('get_time.php', function(data){
// The variable 'data' should equal the result from the PHP time() function!
alert(data);
})
If you're using php (which you mention below), put the time in the page at first load and then you can use Javascript to show that and update it, without making repeated ajax calls.
Not sure what server sided technology you are using, but you could always make an ajax call to the server to get the server time, and then use that in your Javascript to create a new date time object and then continue with your logic as above.
Other reply says to write a script to get the time by ajax, but why output a page then ajax back to the server? You want your server time, echo it in the first place. PHP example:
<?php echo '<script>var today=new Date("'.date("Y-m-d H:i:s").'");</script>'; ?>
If you just want the time to display and not do anything with it echo date("jS F Y H:i");
for example
PHP can achieve it, but it might not be as flexible if the javascript needs to invoke the function to display time without refreshing the entire page each time it does so.
Depending on the requirement. In that case, just use AJAX to send http requests with the backend php to echo back the time to the javascript.