Dave, being a new web developer I would like to know how I can code for a numeric value to decrease by 1 every 24 hours based on the local time function.
Specifically, we are trying to create a reminder for our employees of an upcoming DoD audit in the facility. The count down will represent the number of days remaining before it’s conducted. So what I need to do is begin with a date
and start the countdown from there. What is the code that I should use?
This is an obvious situation where JavaScript is going to be your friend, and it turns out that this is a straightforward application of JavaScript so it should be fairly easy.
The key is to realize that JavaScript is a so-called object oriented programming language and that it has a specific date object with “methods” that let you set and extract specific values. If you need more advanced object-oriented programming features in JavaScript, you can use JavaScript++ to create a JavaScript class.
But, really, this task is even easier than that, because all we need to do is set a specific target date in the future, get the current date, then calculate the amount of time between them and divide it out so that we end up with days as the value.
You get the current date in JavaScript with new Date(), and it turns out that if you specify a date in the parens, it instantiates (creates) a new object with the specified date, rather than today. Want to have a date object with 28 February, 2005 as the specified date? Use new Date(“28 February, 2005”) and it’ll work just fine.
Then we want to work with what us Unix types call the “epoch time” which is the number of milliseconds since a fixed point in the past. For convenience, it’s 1 Jan, 1970 on most systems, but if you think about it you’ll realize that it doesn’t matter what date the epoch time starts with, as long as it’s consistent across both values. Anyway, let’s see some code!
<script language="javascript" type="text/javascript"> today = new Date(); todayEpoch = today.getTime(); target = new Date("28 February, 2005"); targetEpoch = target.getTime(); daysLeft = Math.floor(((targetEpoch - todayEpoch) / (60*60*24)) / 1000); </script>
This JavaScript code snippet, which I’d put in the HEAD of my document, calculates the number of days left until the target date and saves it in the variable daysLeft. Notice that since we’re actually working in milliseconds and we want days, we need to divide by 1000 to get seconds, then divide by 60 (to get minutes), 60 again (to get hours) and then 24 (to get days). Finally, we use the mathematical floor function to make sure we don’t get weird values like 23.434233 days or similar, as a convenience.
Whenever you want to actually include that value on the page, simply add a single line of JavaScript within the HTML code:
<script>document.write(daysLeft);</script>
To put it all together, here’s a simple little page that has both JavaScript code pieces displayed:
<html> <head> <title>JavaScript Countdown timer test</title> <script language="javascript" type="text/javascript"> today = new Date(); todayEpoch = today.getTime(); target = new Date("28 February, 2005"); targetEpoch = target.getTime(); daysLeft = Math.floor(((targetEpoch - todayEpoch) / (60*60*24)) / 1000); </script> </head> <body> <h1>DoD inspection in <script>document.write(daysLeft);</script> days. Are you ready? </h1> </body>
I hope that’ll help you create what you need on your site, and good luck with your DoD inspection too!
Hi there,
I am seeing people help each other in this web page .:)I am a freelancer.Was planning to develop a very basic timer function for nokia s-40 phone.As u all know nokia uses webtools to develop web apps. which uses html, css, js (with mwl functionality).Can you please provide me some basic timer code using the same…
Are peoples here have the free version of full customize countdown Javascript ?
I need it !
Hi guys, I found here: http://www.flashxml.net/countdown.html a countdown which can be set to use the server time. Looks pretty good and it’s very customizable. Hope it will help someone.
hi i am creating a online exam project .how submit a form automatically after the count down finishes
i want to make a javascript from who make a new post in my website. but i was fail to do this plz some help me
Hi, nice post. We started down this road for our auction timers but ended up using a jquery plugin. Keep the posts coming 🙂
Jaya, I asked a Javascript programming geek pal of mine about this, and here’s his response:
In case this is all they gave you, they’re actually instantiating a date object:
date = new Date()
and calling an instance method “getTime” on it:
date.getTime()
It’s returning epoch time in milliseconds, ie: milliseconds since January 1, 1970 12:00am. It’s been 13 digits since 2001, and it will roll over to 14 digits during the evening of Nov 20, 2286. So… probably past the lifespan of the application.
Whether or not it’s a safe thing to use as a sequencing value, is a matter for people far better at statistics than I. (What are the odds of two users managing to do the same action in the same millisecond? I have no idea.)
I am planning to use date.getTime() javascript function and using it as a sequence number. I have some processing based on this number. I am assuming that this is a 13 digits number. Is there a chance that it will come less or more than 13? Also, if a leading Zero is there, is that going to be truncated? Please respond. Thanks
Re:How do I create a JavaScript countdown timer on my Web page?
Hello Everyone,
I write a nice one article on simple timer in javascript, please check out the following url for more details………
http://mindstick.com/Articles/e98037b8-29cc-4419-9158-a6542e29f276/?Creating%20Simple%20Timer%20in%20Java%20Script
Thanks a lot!!!!!
thanks alot,
very good tutorial
I want to use a countdown counter to track quantity remaining based on the quantity entered by a user in a web form once the form is submitted. I have no clue how to do it. Can you help? I’ll tip…
SimpleNTP implementation , hope this can help you.
read my blog “time synchronization in html page with javascript”.
hi frnz..
i’m doing my webdesigning project now nd i want a basic javascript timer program to automatically close a page when the time exceeds 10 seconds… plz help me…
Thanks Dave!
Worked a treat
hi
i have a problem , we are developing a online exam projects now how can we integrate a timer with this. like if our max time for exam is 30 min then after 30 min automatically it should stop the exam and declare the result
i have a problem , we are developing a online exam projects now how can we integrate a timer with this. like if our max time for exam is 40 min then after 40 min automatically it should stop the exam and declare the result
hi ..i am making the online quiz in jsp…could u tell me hw to insert the counter..like after 10 min the quiz ends…only time involment.
Hi,
I am using a script on my website (server) (see below)
I have two questions:
1. when I go to my website and the page with the countdown script is running, it counts down from 1 hour. But if I refresh the page it starts again. How do I change this so the count down is based on the timer on the server and not the client as it is now? The count down should start as soon as the script is enabled so the count down is shown exactly to all looking at the page, regardless of time zones!
2. Where can I change the count down time in the script? e.g if I want to change the countdown time to 2 hours?
———————————–
function DateStringToDateObject( dateString )
{
var theDateTime = null;
try
{
theDateTime = new Date(dateString);
if( theDateTime == “Invalid Date” )
throw new Error(‘Invalid Date Format: ‘ + dateString);
return theDateTime;
}
catch( exception )
{
// JavaScript doesn’t accept: MM-DD-YYYY hh:mm:ss – so we handle that here…
// See if the string is in a format we handle, but JavaScript doesn’t.
// TODO: Come up with a regular expression for our supported date formats.
// This functionality assumes MM-DD-YYYY hh:mm:ss
// TODO: Change it to handle more varieties and extract Month, Date and Year accordingly
var dateTimeParts = dateString.split(” “);
var dateParts = dateTimeParts[0].split(/[-\/]/);
var timeParts;
if( dateTimeParts.length > 1 )
timeParts = dateTimeParts[1].split(“:”);
//theDateTime = new Date();
var m = null;
var d = null;
var y = null;
var hr = null;
var min = null;
var sec = null;
// Extract date parts
if( dateParts.length > 0 )
{
m = parseInt(dateParts[0], 10) – 1; // I had to force 10-based to cover amiguity (padded with zero numbers like 03)
d = parseInt(dateParts[1], 10);
y = parseInt(dateParts[2], 10);
}
// Extract time parts.
if( timeParts && timeParts.length > 0 )
{
hr = parseInt(timeParts[0], 10);
min = parseInt(timeParts[1], 10);
sec = parseInt(timeParts[2], 10);
}
theDateTime = new Date(y, m, d, hr, min, sec);
return theDateTime;
}
}
//====================================================================
/*
CreateCountdown
iTitle: The title for the Countdown Timer (a div within the whole timer div)
iCountdownDate: Must be passed in the format (“MM-DD-YYYY hh:mm:ss”)
iAttachToElement: the Element Node you want the timer attached as a child to.
examples: document.body
document.getElementById(‘myDiv’)
document.body.myDiv
iCountdownNodeId (optional): the Id you want the elements to have.
The following id’s will be assigned if you pass “countdownDiv” as
iCountdownNodeId:
[ iTitle gets put here]
[ timer data is updated here ]
*/
//====================================================================
function CreateCountdown( iTitle, iCountdownDate, iAttachToElement, iCountdownNodeId )
{
var nodeId = ‘countdownDiv’;
if( iCountdownNodeId && typeof(iCountdownNodeId) == ‘string’ && iCountdownNodeId.length > 0 )
nodeId = iCountdownNodeId;
var rightNow = new Date();
var endDate = DateStringToDateObject(iCountdownDate);
if( rightNow.getTime() >= endDate.getTime() )
{
// I’m torn on throwing an error… cause it will start throwing it as soon as a timer expires… the next hit to the page.
// We’ll leave it out for now – possibly as an extra parameter later for debugging.
//iAttachToElement.innerHTML += “CreateCountdown Exception: Invalid Date/Time (Trying to create Countdown with ID: ‘” + nodeId + “‘)”;
return false; //break out so an interval doesn’t start.
}
if( iAttachToElement )
{
var countdownDiv = document.createElement(‘div’);
countdownDiv.id = nodeId;
countdownDiv.className = ‘countdownContainer’;
countdownDiv.endDateMilliseconds = endDate.getTime();
var titleDiv = document.createElement(‘div’);
titleDiv.id = nodeId + ‘-title’;
titleDiv.className = ‘countdownTitle’;
titleDiv.innerHTML = iTitle;
countdownDiv.appendChild(titleDiv);
var timerDiv = document.createElement(‘div’);
timerDiv.id = nodeId + ‘-timer’;
timerDiv.className = ‘countdownTimer’;
countdownDiv.appendChild(timerDiv);
countdownDiv.interval = setInterval(‘UpdateTimer(document.getElementById(“‘ + nodeId + ‘”));’, 1000);
iAttachToElement.appendChild(countdownDiv);
}
}
function UpdateTimer( iCountdownNode )
{
var now = new Date();
if( iCountdownNode && ((iCountdownNode.endDateMilliseconds – now.getTime()) > 0) )
{
var timerNodeId = iCountdownNode.id.split(“-“)[0];
var timerDiv = document.getElementById(timerNodeId + ‘-timer’);
var timeStr = “”;
var diff = iCountdownNode.endDateMilliseconds – now.getTime(); //returned in milliseconds
//convert to Days, Hours, Minutes, Seconds
var msPerSec = 1000;
var msPerMin = 60 * msPerSec;
var msPerHour = 60 * msPerMin;
var msPerDay = 24 * msPerHour;
var days = Math.floor(diff/msPerDay);
var left = diff % msPerDay;
var hours = Math.floor(left/msPerHour);
left = left % msPerHour;
var min = Math.floor(left/msPerMin);
left = left % msPerMin;
var sec = Math.floor(left/msPerSec);
timeStr = min + ” minutes ” + sec + ” seconds”;
timerDiv.innerHTML = timeStr;
}
else
{
clearInterval(iCountdownNode.interval)
iCountdownNode.parentNode.removeChild(iCountdownNode);
}
}
function AddCountdownTester( iCountdownSeconds, iAttachToElement )
{
var testerId = ‘ctTester’;
if( document.getElementById(testerId) )
return;
var dtDelim = “-“;
var tmDelim = “:”;
var maxSeconds = 59;
var dt = new Date();
var s = dt.getSeconds() + iCountdownSeconds;
if( s > maxSeconds )
{
dt.setMinutes(dt.getMinutes() + 1); //increment minutes and get seconds back to real.
s = 0 + (s – maxSeconds);
}
dt.setSeconds(s);
/*
var m = dt.getMonth() + 1;
var d = dt.getDate();
var y = dt.getFullYear();
var h = dt.getHours();
var i = dt.getMinutes();
var s = dt.getSeconds() + iCountdownSeconds;
if( s > maxSeconds )
{
i++; //increment minutes and get seconds back to real.
s = 0 + (s – maxSeconds);
}
*/
var dateStr = MDYHIS_DateString(dt);
var parentElement = (!iAttachToElement) ? document.body : iAttachToElement;
CreateCountdown(“”, dateStr, parentElement, testerId);
}
function MDYHIS_DateString( iDate )
{
var maxSeconds = 59;
var maxMinutes = 59;
var maxHours = 23;
var dateDelim = ‘-‘;
var timeDelim = ‘:’;
var dt = iDate;
var m = dt.getMonth() + 1;
var d = dt.getDate();
var y = dt.getFullYear();
var h = dt.getHours();
var i = dt.getMinutes();
var s = dt.getSeconds();
return (m + dateDelim + d + dateDelim + y + ” ” + h + timeDelim + i + timeDelim + s);
}
// Debug stuff
//document.getElementById(‘debug’).innerHTML += “” + “”;
Hi Dave,
I am looking for a countdwn timer like you describe here.
My issue is that I need the timer to use the server clock not the user’s PC clock as this will be used by people from their homes.
Do you have any example PHP code that I could use to accomplish this task??
Thanx!
Hi Dave,
I wanted to know how can i add a timer in HTML/ASP.NET which would help my students and other users to give the test in that specific time.
Like if i am giving any exam which has a duration of 1 min then how does the countdown timer goes on decreasing by 1 sec.
I mean the user must be able to answer the question within the specified time if he does then the answer will be accepted otherwise the question must be skipped.
What can i do for this to happen in my website.
Please reply as soon as you can.
Thank you.
I was looking at your countdown script above but i have been looking for a script to do the following but can’t find one. Can you help me please?
I want a countdown script that will count down to midnight server time each day and automatically start over and over each day. As long as it hits midnight it will just start over counting down to midnight again each day.
I don’t know if it can be done but if you know of any script or have any advice for me i will certainly appreciate it.
hello sir,
I am writing an examination program in ASP.NET that will time student for 30 min after the time elapse the page will move to the next exam page.
please how can i achieve this, for my project.
thanks very much
i appriciate that timer ..
Dave,
I have one time count down code based on value fetching from database.It’ working fine.But the problem now I have some moification.When I click on the button the time I want to increment by 20 seconds.How can I do this.
Here I included code for your reference.
Thanks in advance.
—-
Multiple Countdown Clocks
[clock1]
[clock2]–>
StartCountDown(“clock1″,”06/27/2010 12:33 PM -0400”)
StartCountDown(“clock2″,”06/27/2010 2:00 PM -0400”)
/*
Author: Robert Hashemian (http://www.hashemian.com/)
Modified by: Munsifali Rashid (http://www.munit.co.uk/)
Modified by: Tilesh Khatri
*/
function StartCountDown(myDiv,myTargetDate)
{
var dthen = new Date(myTargetDate);
var dnow = new Date();
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(myDiv,gsecs);
}
function Calcage(secs, num1, num2)
{
s = ((Math.floor(secs/num1))%num2).toString();
if (s.length 0)
{
document.getElementById(myDiv).innerHTML = DisplayStr;
setTimeout(“CountBack(‘” + myDiv + “‘,” + (secs-1) + “);”, 990);
}
else
{
document.getElementById(myDiv).innerHTML = “Auction Over”;
}
}
Thanks for asking, Harry!! Here ya go:
https://www.askdavetaylor.com/buy-dave-a-cuppa.html
🙂
Hello from Calgary … Thanks for the time-saving advice… Where’s the tip-jar?
Thx, it helped a lot!
I am trying to build a timer much like this, that will allow me to do the following
Set a number of days. have the timer count down to the last min up untill that last day
once it hits that point it will restart and count down 7 days again, lets say for example i wanted it to end on Monday 9:00pm and on monday it stops for 1 hour then starts back counting from monday at 10:00pm untill 9:00pm is this posible to do?
It was very helpful but how do I change the color
After constantly searching the web for a whole day this is by far the most straightforward and perfect solution to what I was looking for.
The only problem I’m facing now is how to apply a css style to the “days” remaining generated result.
Any ideas?
Many thanks for the code Dave.
Great work.
hi
i have a problem , we are developing a online exam projects now how can we integrate a timer with this. like if our max time for exam is 40 min then after 40 min automatically it should stop the exam and declare the result
thanks
I need a clck that will restart every week… it will count down to sunday @ 9:30 AM and on that time restart for next week can you help me with this? i would be greatful…
John Damron
i write the java script code for handling the time
but it have the 25 to 75 ms dealay per seconds & finally in 10 minutes i got the 30 to 45 seconds dealay in my code in mozila 2.0 & but in IE it is working fine how can i solve it
please check the url
http://www.howtocreate.co.uk/tutorials/javascript/timers
I have this Java script created and looking to improve it. I want to have the script start automatically once I open the html without having to click start. Also I want to have it clear the cache in Internet Explorer. Any Help or suggestions would be appreciated.
The script changes the web page every 45 seconds and it works continuously.
= siteCount)
sitesIndex = 0;
var myRef = window.open(‘http://’+sites[sitesIndex++],”myWind”, ‘left=20,top=20,width=500,height=500,toolbar=1,resizable=1’);
}
}
// –>
Start
I created this PHP-Javascript Countdown Timer. The PHP is to fetch server time. You can set it to any timezone you want. And the Javascript is for the animation…
This way it will end at the same time, no matter where geographically your website visitor is.
Full instructions included. Enjoy…
http://www.minisitegallery.com/blog/php-javascript-countdown-script-with-timezone-setting.html
i have a website with a javatimer on it is there a javascript i can put in to stop it? and is there any way i can stop a timer that isnt javascript?
Many Thanks Crackruckles
I am using your coutdown timer, however, instead of changing the date count each day at midnight it changes it at roughly noon. The only thing I changed in the code is the date we need it to count down to. Any advice on what I am doing wrong?
I want to send a mail automataically to a client afer 1 hour from my jsp page by using Javascript?
I am looking to make a countdown clock for my webpage…. I don’t have it published yet as I am not done with it…
hi
i have a problem , we are developing a online exam projects now how can we integrate a timer with this. like if our max time for exam is 30 min then after 30 min automatically it should stop the exam and declare the result
First of all I know nothing about html. I want to add the timer that you see if you go to the link below. I want to put that timer or create my own and put it on my Facebook profile. Is this possible and how? Thanks
Hi
I Want To Set reminder In JSP Usingign JavaScript How I Set ??
If you need one that works on myspace, check out this page Here
thanks alot for the reply
hi
i have a problem , we are developing a online exam projects now how can we integrate a timer with this. like if our max time for exam is 30 min then after 30 min automatically it should stop the exam and declare the result
thanks
Damien, pop over to Google and check out the results for “javascript millisecond timer”. There are some interesting choices out there, and, yes, you can time down to the millisecond granularity.
Hi,
I am enquiring about timing systems online. I am looking for a very accurate timing mechanism to incorporate into my website to evaluate correct
responses and the time it took to complete an exercise. This will be down to the millisecond. The timing mechanism should begin when the user
clicks a button and will end in the same way – at the push of an onscreen button. It would be great if the software could display a counter online as well. Any ideas on what I should go with?
Absolutely right, David. Since the person submitting the question was talking about a controlled work environment, I made the leap that they’d have standardized on a network time synchronization protocol and everyone would have the correct time on their computers, plus or minus a few seconds. If that’s not true, then some people are definitely going to see odd results, but perhaps we can conclude that they receive less attention from IT and are therefore less critical to the success of the audit in the first place? (I know, this is pretty weak logic. Cut me some slack, okay? 🙂 )
I’d just like to point out, because this is javascript, its client side. So it will use whatever system time the user’s computer is set at. Not saying your user’s will have their local computer’s system dates set so bad it will make a difference, but I just wanted to point out its totally on their side. If you have some sort of server side technology at your disposal, such as ASP, ASP.NET, JSP, etc, then you could better control it. Such as by setting seed value and then letting the client side javascript take the count down from there.
How can I add a JavaScript countdown timer on my Web page?
Dave, being a new web developer I would like to know how I can code for a numeric value to decrease by 1 every 24 hours based on the local time function. Specifically, we are trying to create a…