Found this daily countdown timer and edited it a little but I find it a little long and learned that Jquery is a shorter notation of javascript but don't know anything about it.
My knowledge is not advanced enough to either shorten this or change it to jquery.
I use the <body onload = "getSeconds()"> to start the daily countdown.
var reloadPage = false;
function getSeconds()
{
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var midnight = new Date(now.getFullYear(),now.getMonth(),now.getDate(),21,57,0); //midnight 0000 hrs
//midnight - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var ft = midnight.getTime() + 86400000; // add one day 86 400 000
var diff = ft - time;
diff = parseInt(diff/1000);
if (diff > 86400) {diff = diff - 86400}
startTimer (diff);
}
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else
{
clearInterval(ticker); //stop counting at zero
if (secs == 0)
{
reloadPage = true;
console.log("reset");
};
getSeconds(); //and start again if required
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
if(reloadPage)
{
var result = "Please reload page for daily reset."
}
else
{
var result = ((hours <= 0 ) ? "" : hours + " hours ") + ( (mins <= 0) ? "" : mins + " minutes " ) + ( (mins <= 0) ? " < 1 minute " : "" );
}
document.getElementById("countdown").innerHTML = "Daily reset: " + result;
}
Here's your code "changed to jQuery"
var reloadPage = false;
function getSeconds()
{
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var midnight = new Date(now.getFullYear(),now.getMonth(),now.getDate(),21,57,0); //midnight 0000 hrs
//midnight - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var ft = midnight.getTime() + 86400000; // add one day 86 400 000
var diff = ft - time;
diff = parseInt(diff/1000);
if (diff > 86400) {diff = diff - 86400}
startTimer (diff);
}
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); //to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else
{
clearInterval(ticker); //stop counting at zero
if (secs == 0)
{
reloadPage = true;
console.log("reset");
};
getSeconds(); //and start again if required
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
if(reloadPage)
{
var result = "Please reload page for daily reset."
}
else
{
var result = ((hours <= 0 ) ? "" : hours + " hours ") + ( (mins <= 0) ? "" : mins + " minutes " ) + ( (mins <= 0) ? " < 1 minute " : "" );
}
$("#countdown").html("Daily reset: " + result);
}
saving 27 bytes ... I'm sure loading 86000+ bytes of jQuery library wont negate this saving at all
a shorter implementation, imo. simpler, and no need for jQuery (even if you've already loaded it)
//a few values that come in handy when dealing with timestamps
MILLISECOND = MILLISECONDS = 1;
SECOND = SECONDS = 1000*MILLISECONDS;
MINUTE = MINUTES = 60*SECONDS;
HOUR = HOURS = 60*MINUTES;
DAY = DAYS = 24*HOURS;
TIMEZONE_OFFSET = new Date().getTimezoneOffset() * MINUTES;
var midnight = Date.now() + DAY - (Date.now() - TIMEZONE_OFFSET) % DAY;
function updateCountdown(){
//an utility to fetch the parts (hours, mins, ...) of the time
//and return a formated output
function fetch(factor, postfix){
var value = Math.floor(t/factor);
t %= factor; //beware: side-effect
//format the value
return value > 0?
value + (postfix == null? "": postfix):
"";
}
var t = midnight - Date.now(); //time till midnight
var countdown = document.querySelector("#countdown");
if(t <= 0){
countdown.innerHTML = "Please reload page for daily reset.";
location.reload();
}else{
countdown.innerHTML = [
"Daily reset:",
fetch(HOURS, " hours"),
fetch(MINUTES, " minutes"),
fetch(SECONDS, " seconds")
].join(" ");
setTimeout(updateCountdown, 200);
}
}
updateCountdown();
Edit:
how would I change the time to be resetted at
the variable midnight holds the target-timestamp I am counting to: t = midnight-Date.now()
change the target timestamp.
//a utility that gives you the timestamp for today `00:00 AM` (in your local timezone)
function today(){
var now = Date.now();
return now - (now - TIMEZONE_OFFSET) % DAY;
}
console.log( new Date( today() ) ); //today 00:00:00 GMT+yourTimeZoneOffset
define a target timezone:
var midnight = today() + 1*DAY;
var target = today() + 20*HOURS + 45*MINUTES + 59*SECONDS;
//you see how these constants get handy ;)
and compute the time to that target:
var t = target - Date.now();
the rest is the same
Related
Hi I've been trying to take and work with some code that I can get partially working, I want a countdown that we can set an end time it counts down to (obvious is obvious out of the way), we also want to set it to show at only certain times of the day and only certain days of the week.
I've managed to get the below working so we can set a time of the day to show but I can't get it to work so it only shows on the certain specified days. Can anyone help please?
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
if (d.getHours() >= 7 && d.getHours() <= 15) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
[EDIT]
Just to add to this I tried changing part of the script to this but it didn't work:
$(function() {
$("#countdown").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 1 || day == 2) {
//gets the current time.
var d = new Date();
if(d.getHours() >= 7 && d.getHours() <= 10 ){
$("#countdown").show();
}
else {
$("#countdown").hide();
}
} else {
$("#countdown").hide();
}
}
});
});
Whatever you did is all good except the setInterval part where you are passing the string value as setInterval("tick()", 1000) instead of a function reference as setInterval(tick, 1000)
Also, I have updated the code as below to check the specific day along with specific hours which you had,
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
}
You can give a try below,
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval(tick, 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
$("#countdown").hide();
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged in to the current time.
Here is my code:-
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var markMinutes = markDate.getMinutes();
var markSeconds = markDate.getSeconds();
var currDate = new Date();
var currMinutes = currDate.getMinutes();
var currSeconds = currDate.getSeconds();
var minutes = currMinutes - markMinutes;
if(minutes < 0) { minutes += 60; }
var seconds = currSeconds - markSeconds;
if(seconds < 0) { seconds += 60; }
if(minutes < 10) { minutes = "0" + minutes; }
if(seconds < 10) { seconds = "0" + seconds; }
var hours = 0;
if(minutes == 59 && seconds == 59) { hours++; }
if(hours < 10) { hours = "0" + hours; }
var timeElapsed = hours+':'+minutes+':'+seconds;
document.getElementById("timer").innerHTML = timeElapsed;
setTimeout(function() {updateClock()}, 1000);
}
The output is correct upto 00:59:59 but after that that O/P is:
00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00
How can I solve this and is there a more efficient way I can do this?
Thank you.
No offence, but this is massively over-enginered. Simply store the start time when the script first runs, then subtract that from the current time every time your timer fires.
There are plenty of tutorials on converting ms into a readable timestamp, so that doesn't need to be covered here.
var start = Date.now();
setInterval(function() {
document.getElementById('difference').innerHTML = Date.now() - start;
// the difference will be in ms
}, 1000);
<div id="difference"></div>
There's too much going on here.
An easier way would just be to compare markDate to the current date each time and reformat.
See Demo: http://jsfiddle.net/7e4psrzu/
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var currDate = new Date();
var diff = currDate - markDate;
document.getElementById("timer").innerHTML = format(diff/1000);
setTimeout(function() {updateClock()}, 1000);
}
function format(seconds)
{
var numhours = parseInt(Math.floor(((seconds % 31536000) % 86400) / 3600),10);
var numminutes = parseInt(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60),10);
var numseconds = parseInt((((seconds % 31536000) % 86400) % 3600) % 60,10);
return ((numhours<10) ? "0" + numhours : numhours)
+ ":" + ((numminutes<10) ? "0" + numminutes : numminutes)
+ ":" + ((numseconds<10) ? "0" + numseconds : numseconds);
}
markPresent();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="timer"></div>
Here is a solution I just made for my use case. I find it is quite readable. The basic premise is to simply subtract the timestamp from the current timestamp, and then divide it by the correct units:
const showElapsedTime = (timestamp) => {
if (typeof timestamp !== 'number') return 'NaN'
const SECOND = 1000
const MINUTE = 1000 * 60
const HOUR = 1000 * 60 * 60
const DAY = 1000 * 60 * 60 * 24
const MONTH = 1000 * 60 * 60 * 24 * 30
const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
// const elapsed = ((new Date()).valueOf() - timestamp)
const elapsed = 1541309742360 - timestamp
if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s`
if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m`
if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h`
if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d`
if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo`
return `${Math.round(elapsed / YEAR)}y`
}
const createdAt = 1541301301000
console.log(showElapsedTime(createdAt + 5000000))
console.log(showElapsedTime(createdAt))
console.log(showElapsedTime(createdAt - 500000000))
For example, if 3000 milliseconds elapsed, then 3000 is greater than SECONDS (1000) but less than MINUTES (60,000), so this function will divide 3000 by 1000 and return 3s for 3 seconds elapsed.
If you need timestamps in seconds instead of milliseconds, change all instances of 1000 to 1 (which effectively multiplies everything by 1000 to go from milliseconds to seconds (ie: because 1000ms per 1s).
Here are the scaling units in more DRY form:
const SECOND = 1000
const MINUTE = SECOND * 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH = DAY * 30
const YEAR = MONTH * 12
We can also use console.time() and console.timeEnd() method for the same thing.
Syntax:
console.time(label);
console.timeEnd(label);
Label:
The name to give the new timer. This will identify the timer; use the same name when calling console.timeEnd() to stop the timer and get the time output to the console.
let promise = new Promise((resolve, reject) => setTimeout(resolve, 400, 'resolved'));
// Start Timer
console.time('x');
promise.then((result) => {
console.log(result);
// End Timer
console.timeEnd('x');
});
You can simply use performance.now()
Example:
start = performance.now();
elapsedTime = performance.now() - start;
var hours = 0;
if(minutes == 59 && seconds == 59)
{
hours = hours + 1;
minutes = '00';
seconds == '00';
}
I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.
I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be added.
(function(w){
var timeStart,
timeEnd,
started = false,
startTimer = function (){
this.timeStart = new Date();
this.started = true;
},
getPartial = function (end) {
if (!this.started)
return 0;
else {
if (end) this.started = false;
this.timeEnd = new Date();
return (this.timeEnd - this.timeStart) / 1000;
}
},
stopTime = function () {
if (!this.started)
return 0;
else {
return this.getPartial(true);
}
},
restartTimer = function(){
this.timeStart = new Date();
};
w.Timer = {
start : startTimer,
getPartial : getPartial,
stopTime : stopTime,
restart : restartTimer
};
})(this);
Start
Partial
Stop
Restart
What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):
var trace = console.log
function elapsed(op) {
this.op = op
this.t0 = Date.now()
}
elapsed.prototype.show = function() {
trace.apply(null, [this.op, 'msec', Date.now() - this.t0, ':'].concat(Array.from(arguments)))
}
to be used - for instance:
function debug_counters() {
const e = new elapsed('debug_counters')
const to_show = visibleProducts().length
e.show('to_show', to_show)
}
I use the following javascript to show a countdown timer for shipping that day
var timerRunning = setInterval(
function countDown() {
var target = 14; // This is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
var despatchday = 'TODAY!';
if (weekday == 0) { //Sunday? Add 24hrs
target += 24;
despatchday = 'on Monday';
} //keep this before the saturday, trust me :>
if (weekday == 6) { //It's Saturday? Add 48hrs
target += 48;
despatchday = 'on Monday';
}
if ((weekday == 5) && (now.getHours() > target) && (now.getHours() <= 24)) {
target += 72;
despatchday = 'on Monday';
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if ((weekday >= 1) && (weekday <= 5)) {
if ((now.getHours() > target) && (now.getHours() <= 24)) { //stop the clock
target += 24;
despatchday = 'tomorrow';
} else if (now.getHours() > target) { //stop the clock
return 0;
despatchday = 'today';
}
}
var hrs = (target) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = 'Order in the next ' + hrs + 'hrs ' + mins + 'mins ' + secs + 'secs for despatch ' + despatchday;
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
The problem I have is that if I set the cut off time to anything other than a full hour the timer does not work.
The correct output is Order in the next xx hrs, xx mins xx secs for despatch today
If I set
var target = 14; // This is the cut-off point
as 14:30 it gives "Just checking the time"
I assumed that it needed the mins as a decimal but if I set it as 14.5 it is adding 0.5 hrs to the output; ie 23.5hrs 50mins 30secs
I have set up a fiddle here. http://jsfiddle.net/4eu4o6k0/
Ideally I need it to be able to handle time in the format of hh:mm as that is the format of the time stored in the database. Is there a correct way to process partial hours in this type of script?
you need to hand the decimal place of hrs:
var rem =hrs%1;
mins = mins + (rem*60);
hrs = hrs - rem;
if (mins > 59) {
mins = mins - 60;
hrs= hrs +1;
}
Also I think you meant to spell dispatch
I'd personally advise against writing own code for handling time intervals because it's known to be error-prone. Use moment.js or date.js for such things
Here's sample for Moment.js
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript to run the Clock (date and time) 4 times speeder
I'm trying to make a clock that starts at a time value (hh:mm:ss) that I've supplied, and runs at 4x speed (for the server time of an online game that runs 4x actual time). I've modified a free clock that I found online to do this, but it only works for every other minute (try the code below to see exactly what I mean if that doesn't make sense).
var customClock = (function () {
var timeDiff;
var timeout;
function addZ(n) {
return (n < 10 ? '0' : '') + n;
}
function formatTime(d) {
t1 = d.getHours();
t2 = d.getMinutes();
t3 = d.getSeconds() * 4;
if (t3 > 59) {
t3 = t3 - 60;
t2 = t2 + 1;
}
if (t2 > 59) {
t2 = t2 - 60;
t1 = t1 + 1;
}
if (t1 > 23) {
t1 = 0;
}
return addZ(t1) + ':' + addZ(t2) + ':' + addZ(t3);
}
return function (s) {
var now = new Date();
var then;
var lag = 1015 - now.getMilliseconds();
if (s) {
s = s.split(':');
then = new Date(now);
then.setHours(+s[0], +s[1], +s[2], 0);
timeDiff = now - then;
}
now = new Date(now - timeDiff);
document.getElementById('clock').innerHTML = formatTime(now);
timeout = setTimeout(customClock, lag);
}
}());
window.onload = function () {
customClock('00:00:00');
};
Any idea why this is happening? I'm pretty new to Javascript and this is definitely a little hack-ey. Thanks
i take the orginal time and substract it from the current then multiply it by 4 and add it to the orginal time. I think that should take care or the sync problem.
(function(){
var startTime = new Date(1987,08,13).valueOf() //save the date 13. august 1987
, interval = setInterval(function() {
var diff = Date.now() - startTime
//multiply the diff by 4 and add to original time
var time = new Date(startTime + (diff*4))
console.log(time.toLocaleTimeString())
}, 1000)
}())
How to use with a custom date (use the Date object)
Date(year, month, day, hours, minutes, seconds, milliseconds)
var lag = 1015 - now.getMilliseconds(); is attempting to "run this again a smidge (15 ms) after the next clock tick". Make this value smaller (divide by 4?), and this code will run more frequently.
Next up, get it to show 4x the current clock duration. Similar problem: multiply now's details by 4 either inside or outside formatTime()
I would first create a Clock constructor as follows:
function Clock(id) {
var clock = this;
var timeout;
var time;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.stop = stop;
this.start = start;
var element = document.getElementById(id);
function stop() {
clearTimeout(timeout);
}
function start() {
timeout = setTimeout(tick, 0);
time = Date.now();
}
function tick() {
time += 1000;
timeout = setTimeout(tick, time - Date.now());
display();
update();
}
function display() {
var hours = clock.hours;
var minutes = clock.minutes;
var seconds = clock.seconds;
hours = hours < 10 ? "0" + hours : "" + hours;
minutes = minutes < 10 ? "0" + minutes : "" + minutes;
seconds = seconds < 10 ? "0" + seconds : "" + seconds;
element.innerHTML = hours + ":" + minutes + ":" + seconds;
}
function update() {
var seconds = clock.seconds += 4;
if (seconds === 60) {
clock.seconds = 0;
var minutes = ++clock.minutes;
if (minutes === 60) {
clock.minutes = 0;
var hours = ++clock.hours;
if (hours === 24) clock.hours = 0;
}
}
}
}
Then you can create a clock and start it like this:
var clock = new Clock("clock");
clock.start();
Here's a demo: http://jsfiddle.net/Nt5XN/
Let me first say I do not have a deep understanding of javascript but I know how to work my way around enough to write small scripts for pages. A client of mine needs me to do the following for a website:
Find the user's local time on their computer.
Take that local time and subtract it from 6pm.
Display that time in a countdown or just a statement letting the user know how much time is left for same day shipping.
After 6pm the time resets or disappears until the next business day.
So far I've been able to create the logic for getting the time from the local computer. I thought I'd be able to use datejs but it does not calculate hours in a day.
Here is the current code I have:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
var suffix = "AM";
if (hours >= 12)
{
suffix = "PM";
hours = hours - 12;
}
if (hours == 0)
{
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
How about this:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (minutes < 10)
minutes = "0" + minutes
if (suffix == "PM" && hours >= 6)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 5 - hours;
var minsLeft = 60 - minutes;
document.write("<b> You've got " + hoursLeft + " hours and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
if this site would let me comment on other people's answers I'd give the credit for this to Giovanni, but since I can't yet comment on other people's work, here's what needs to change.
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (minutes < 10)
minutes = "0" + minutes
if (hours >= 18)
{
document.write("You're too late for next day shipping!");
}
else
{
var hoursLeft = 17 - hours;
var minsLeft = 60 - minutes;
if(minsLeft==60){
minsLeft=0;
hoursLeft++;
}
document.write("<b> You've got " + hoursLeft + " and " + minsLeft + " minutes left to qualify for next day shipping! </b>")
}
The reason for this is that people who are ordering at 5AM might see think that they have to submit within the next hour for their shipping to be next day when in fact they have the next 13 hours.
EDIT: saw your timezone concern and here is a post that might interest you.
EDIT 2: posted the wrong link. The correct one should be up now, though it might be a bit of a dated answer.
Something similar I solved also yesterday, so this is easy. Here is the javascript code:
function start_onload(last_hour){
var timeout_message = document.getElementById('timeout_message');
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var expire_time = 0; // in seconds
if (hours<last_hour) {
expire_time += (last_hour-hours-1)*3600;
expire_time += (59-minutes)*60;
expire_time += (59-seconds);
}
else {
timeout_message.innerHTML = 'It\'s after '+last_hour+' o\'clock!';
return;
}
var expire_time = currentTime.getTime() + 1000*expire_time;
//console.log(expire_time, hours, minutes, seconds, expire_time);
function countdown_session_timeout() {
var current_time = new Date().getTime();
var remaining = Math.floor((expire_time - current_time)/1000);
if (remaining>0) {
hours = Math.floor(remaining/3600);
minutes = Math.floor((remaining - hours*3600)/60);
seconds = remaining%60;
timeout_message.innerHTML = 'Countdown will stop in '+ hours + ' hours ' + minutes + ' min. ' + seconds + ' sec.';
setTimeout(countdown_session_timeout, 1000);
} else {
timeout_message.innerHTML = 'Time is up!';
}
}
countdown_session_timeout();
}
Full script # pastebin.com is here.
This is a simple countdown timer starting at 30 seconds from when the function is run and ending at 0. After reaching 0 it automatically reset the counter. It goes again to 30 second and this process is continued in a loop
window.onload = function() { startCountDown(30,
1000, myFunction); }
function startCountDown(i, p, f) { var pause = p; var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
//fn();
startCountDown(30, 1000, myFunction); //stop
return; } setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
); } //set it going countDownObj.count(i); }
function myFunction(){};
</script>