Link to home
Start Free TrialLog in
Avatar of Marcusw
Marcusw

asked on

How to create a count down timer

i need to create a countdown timer that count down the hours, mins, and seconds on my website.

i nee the time to be based on my server (server based in US but i need to translate to UK time).

i need to countdown till 5pm every day then show a message until 7pm then start the counter again for the next day.

i have very little experience with javascipt so an help is appreciated


thanks

Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Here is a first try


<html>
<head>
<script>
var tId="";
var anHour = 24*60*60*1000;
var twoHours = anHour*2
function countDown() {
  var now = new Date();
  var gmt = new Date(now.getTime() + (now.getTimezoneOffset() * 60000));
  var seventeen = new Date(gmt.getFullYear(),gmt.getMonth(),gmt.getDate(),17,0,0,0);
  var nineteen  = new Date(seventeen.getTime()+twoHours);
  var countTime = new Date(seventeen.getTime()-gmt.getTime());
  var hh = countTime.getHours();
  var mm = countTime.getMinutes();
  var ss = countTime.getSeconds();
  if (mm<10) mm="0"+mm
  if (ss<10) ss="0"+ss
  var text = hh+':'+mm+':'+ss;
  if (gmt>=seventeen&&gmt<=nineteen) text += " - Welcome to the twilight zone";
  
  document.getElementById('timeSpan').innerHTML=text;
}
window.onload=function() { tId=setInterval('countDown()',1000);}
</script>
<span  id="timeSpan" style="position:fixed; top:0;left:500"></span>

Open in new window

 var now = new Date();
 this takes the time of client's browser.
You cannot get server time in javascript, as it is client-side script.
what you can do is generate in some server-side language (PHP,JSP,ASP whatever) a javascript parsable object (with server time).

in java it could look like this:
var now = Date.parse(<%=SomerServerUtilClass.getTimeString()%>);
Avatar of Marcusw
Marcusw

ASKER

great thanks for the code, that seems very close.

I have 2 questions though

where is the time taken from, i need it to be from our server, but this seems to be from the computer as the same page shows different times on 2 different computers

also

the message welcome to the twilight zone only shows for so many seconds, not hours why is this


thanks
ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial