Time Zone Countdown script, not working as intended? - javascript

I was on the lookout for a javascript countdown with adjustable timezones, and found this script called tzcount.js. According to the instructions:
The month can be specified as a number between 1 and 12 to indicate
which month of the year that you are counting down to (it will assume
next year if the month has already past for this year)
But when I enter the value 1 for month, the script tells me that the date has passed, instead of assuming it is the first month of the next year. Am I missing something or is this script not working as intended?
The full script:
<!--Copy and paste just above the close </BODY> of you HTML webpage.-->
<SCRIPT type="text/javascript">
// **** Time Zone Count Down Javascript **** //
/*
Visit http://rainbow.arch.scriptmania.com/scripts/
for this script and many more
*/
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '*'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '1'; // Offset for day of month day or + day
var hour = 0; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(month,day,hour,tz)
{
var toDate = new Date();
if (month == '*')toDate.setMonth(toDate.getMonth() + 1);
else if (month > 0)
{
if (month <= toDate.getMonth())toDate.setYear(toDate.getYear() + 1);
toDate.setMonth(month-1);
}
if (day.substr(0,1) == '+')
{var day1 = parseInt(day.substr(1));
toDate.setDate(toDate.getDate()+day1);
}
else{toDate.setDate(day);
}
toDate.setHours(hour);
toDate.setMinutes(0-(tz*60));
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "Sorry, you are too late.";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = days + " day" + (days == 1 ? '' : 's') + ' + ' +hours+ 'h : ' +mins+ 'm : '+secs+'s';
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}
</SCRIPT>
<p><font face="arial" size="-2">The countdown script at </font><br><font face="arial, helvetica" size="-2">Rainbow Arch</font></p>
I found the script, and the instructions, here http://rainbow.arch.scriptmania.com/scripts/timezone_countdown.html

The script isn't working right.
You need to edit this line:
if (month <= toDate.getMonth())toDate.setYear(toDate.getYear() + 1);
getYear abbreviates, so it returns 115 for this year. setYear then thinks you mean 115 AD, which passed a long time ago.
Replace setYear and getYear with setFullYear and getFullYear. Those functions will return/expect 2015.

Related

Display countdown in user's local time

I want to implement a simple javascript countdown that always counts down to the user's local next Friday, 15:00. I currently use the following code, but I believe that it only displays the countdown to next Friday, 15:00 UTC. Any help would really be appreciated!!
var curday;
var secTime;
var ticker;
function getSeconds() {
var nowDate = new Date();
var dy = 5; //Sunday through Saturday, 0 to 6
var countertime = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 15, 0, 0);
var curtime = nowDate.getTime(); //current time
var atime = countertime.getTime(); //countdown time
var diff = parseInt((atime - curtime) / 1000);
if (diff > 0) {
curday = dy - nowDate.getDay()
} else {
curday = dy - nowDate.getDay() - 1
} //after countdown time
if (curday < 0) {
curday += 7;
} //already after countdown time, switch to next week
if (diff <= 0) {
diff += (86400 * 7)
}
startTimer(diff);
}
function startTimer(secs) {
secTime = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); //initial count display
}
function tick() {
var secs = secTime;
if (secs > 0) {
secTime--;
} else {
clearInterval(ticker);
getSeconds(); //start over
}
var days = Math.floor(secs / 86400);
secs %= 86400;
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
//update the time display
document.getElementById("days").innerHTML = curday;
document.getElementById("hours").innerHTML = ((hours < 10) ? "0" : "") + hours;
document.getElementById("minutes").innerHTML = ((mins < 10) ? "0" : "") + mins;
document.getElementById("seconds").innerHTML = ((secs < 10) ? "0" : "") + secs;
}
function starter() {
getSeconds();
}
Javascript dates are inherently UTC, however the various non–UTC get and set methods all work on local dates and times based on the host system clock and daylight saving settings.
So if you're not using UTC methods, everything in the OP is "local" by default. The following is a simplistic implementation of your "time until next Friday at 15:00" all as local values:
function timeUntil() {
let now = new Date();
// Create date for 15:00 on coming Friday
let friday = new Date(now);
friday.setHours(15,0,0,0);
let dayNum = friday.getDay();
friday.setDate(friday.getDate() + 5 - (dayNum < 6? dayNum : 5 - dayNum));
// If today is Friday and after 15:00, set to next Friday
if (dayNum == 5 && friday < now) {
friday.setDate(friday.getDate() + 7);
}
// Time remaining
let diff = friday - now;
let days = diff / 8.64e7 |0;
let hrs = (diff % 8.64e7) / 3.6e6 | 0;
let mins = (diff % 3.6e6) / 6e4 | 0;
let secs = (diff % 6e4) / 1e3 | 0;
// Display result
document.getElementById('days').textContent = days;
document.getElementById('hrs').textContent = hrs;
document.getElementById('mins').textContent = mins;
document.getElementById('secs').textContent = secs;
document.getElementById('fullDate').textContent = friday.toLocaleString();
}
setInterval(timeUntil, 1000);
td {
text-align: center;
}
<table>
<tr><th>Days<th>Hrs<th>Mins<th>Secs
<tr><td id="days"><td id="hrs"><td id="mins"><td id="secs">
<tr><td id="fullDate" colspan="4">
</table>
Note that setInterval isn't a good way to run a timer over a long period as it drifts (it doesn't run at exactly the specified interval). The overall time will be OK, it will just seem to skip from time to time and drift within a second with respect to the system displayed clock.
Better to use sequential calls setTimeout, calculating the time until just after the next full second each time so it closely matches the system clock's tick.

Making this JS countdown handle minutes

I have a countdown script that enables me to see how much time there is left until a specific date and time in any given timezone. The script has improved alot from its original state (Much thanks to this community) but it still has some flaws.
The script is currently only able to countdown to a specific hour (Like 2015/12/12 18:00) but NOT to a specific minute (Like 2015/12/12 18:25).
I would like to be able to also specify any given minute of the hour (var minute), but I dont know how. Would greatly apreciate if anyone could help me out.
Edit: The timezone variable (var tz) must be taken into account.
Edit2: Solved the issue I got with the first answer, with this: toDate.setMinutes(minutes-(tz*60));
Full script below:
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '11'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '10'; // Offset for day of month day or + day
var hour = 14; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(year,month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(year,month,day,hour,tz)
{
// props to Luke Woodward at Stackoverflow
var now = new Date();
var countdownToYear = now.getFullYear();
var countdownToMonth = now.getMonth();
var countdownToDay = now.getDate();
if (month === '*') {
countdownToMonth += 1;
} else if (month > 0) {
if (month <= now.getMonth()) {
countdownToYear += 1;
}
countdownToMonth = month - 1;
}
if (day.substr(0,1) === '+') {
var day1 = parseInt(day.substr(1), 10);
countdownToDay += day1;
} else {
countdownToDay = day;
}
var toDate = new Date(countdownToYear, countdownToMonth, countdownToDay);
// props to Luke Woodward at Stackoverflow^
toDate.setHours(hour);
toDate.setMinutes(0-(tz*60));
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "<li>0<br><span class='tzcd-format'>day</span></li><li>0<br><span class='tzcd-format'>hours</span></li><li>0<br><span class='tzcd-format'>minutes</span></li><li>0<br><span class='tzcd-format'>seconds</span></li>";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = "<li>" + days + "<br><span class='tzcd-format'>day" + (days == 1 ? '' : 's') + '</span></li>' + "<li>" + hours + "<br><span class='tzcd-format'>hours</span></li> " + "<li>" + mins + "<br><span class='tzcd-format'>minutes</span></li>" +"<li>"+secs+ "<br><span class='tzcd-format'>seconds</span></li>";
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}
I wasn't able to test it but this should be it:
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '11'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '10'; // Offset for day of month day or + day
var hour = 14; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var minutes = '10';
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(year,month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(year,month,day,hour,tz)
{
// props to Luke Woodward at Stackoverflow
var now = new Date();
var countdownToYear = now.getFullYear();
var countdownToMonth = now.getMonth();
var countdownToDay = now.getDate();
if (month === '*') {
countdownToMonth += 1;
} else if (month > 0) {
if (month <= now.getMonth()) {
countdownToYear += 1;
}
countdownToMonth = month - 1;
}
if (day.substr(0,1) === '+') {
var day1 = parseInt(day.substr(1), 10);
countdownToDay += day1;
} else {
countdownToDay = day;
}
var toDate = new Date(countdownToYear, countdownToMonth, countdownToDay);
// props to Luke Woodward at Stackoverflow^
toDate.setHours(hour);
toDate.setMinutes(minutes);
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "<li>0<br><span class='tzcd-format'>day</span></li><li>0<br><span class='tzcd-format'>hours</span></li><li>0<br><span class='tzcd-format'>minutes</span></li><li>0<br><span class='tzcd-format'>seconds</span></li>";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = "<li>" + days + "<br><span class='tzcd-format'>day" + (days == 1 ? '' : 's') + '</span></li>' + "<li>" + hours + "<br><span class='tzcd-format'>hours</span></li> " + "<li>" + mins + "<br><span class='tzcd-format'>minutes</span></li>" +"<li>"+secs+ "<br><span class='tzcd-format'>seconds</span></li>";
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}

JQuery Datepicker - setting MinDate based on current time

I'm using JQuery Datepicker for customers to choose a delivery date. I want to be able to check if the customer is ordering before noon and if so next day delivery is available. If they are ordering after noon, next day delivery is unavailable and so that day is unselectable.
I've got some code to check against the current time but how to I add this value into MinDate in the settings at the top?
Thank you!
<div class="delivery-date">
<p>
<label for="date">Select a date for delivery below:</label>
<input id="date" type="text" name="properties[delivery-date]" readonly="readonly" style="background:white; width:30%" class="required" data-error="Please choose a delivery date." />
</p>
</div>
<script>
jQuery(function() {
jQuery("#date").datepicker( {
// minDate: new Date(((new Date).getTime() + 49 * 60 * 60 * 1000) ),
minDate: checkBeforeNoon,
maxDate: "+2M", // show up to 2 months
dateFormat: 'dd/mm/yy',
beforeShowDay: available_delivery_dates
} );
});
/*========== check time ==========*/
// if time before 12pm, offer next day delivery
function checkBeforeNoon(nextDayDelivery){
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
var nextDayDelivery = '+1d';
} else {
// after 12pm - next day delivery unavailable
var nextDayDelivery = '+2d';
}
function get24Hr(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours*100+minutes;
console.log(time +" - "+hours);
return hours;
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
}
/*========== Make sundays always unavailable ==========*/
function available_delivery_dates(date) {
var sunday = 0; // unavailable for delivery
var mon = 1
var tue = 2;
var wed = 3;
var thu = 4;
var fri = 5;
var sat = 6;
var day_of_week = date.getDay();
var not_sun = day_of_week > 0;
if(not_sun){
var day = date.getDate();
return [true, ''];
}
else{
// all else - do not allow
return [false, ' ', 'Delivery is unavailable on this day'];
}
}
</script>
You already accomplished it. You simply need to add a return to the function that is checking if it is noon. If you want to advise the client that one day shipping is available now, you can do so by adding a log in your function. Here is your code modified:
http://jsfiddle.net/graphicfreedom/L3tz8243/1/
function checkBeforeNoon(nextDayDelivery){
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
var nextDayDelivery = '+1d';
$("#log").html('Next day delivery available! Order before noon!'); //show response to user
} else {
// after 12pm - next day delivery unavailable
var nextDayDelivery = '+2d';
$("#log").html('Next day delivery NOT available! It is already past noon :('); //show response to user
}
return nextDayDelivery;
}
Also, you can easily separate the functions. It is easier to read, and you can always call a function from a function. Hope this helps!
Remove the var before nextDayDelivery in the if-else block as you would be redeclaring it. Then return nextDayDelivery. Also, a good idea to fix the missing semi-colons in the getVal() method.
function checkBeforeNoon(nextDayDelivery) {
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
nextDayDelivery = '+1d'; // REMOVE var FROM HERE
} else {
// after 12pm - next day delivery unavailable
nextDayDelivery = '+2d'; // REMOVE var FROM HERE
}
function get24Hr(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours * 100 + minutes;
console.log(time + " - " + hours);
return hours;
}
function getval() {
// ADD MISSING SEMI-COLONS ON THE FOLLOWING 3 LINES
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
return nextDayDelivery; // ADD RETURN STATEMENT
}

Convert javascript Date() to UTC and offset time

I have a countdown timer on a website (it acts as a same day shipment countdown timer, so the visitor knows if they place an order, it will be shipped out today if they're within the time window.) Basically the timer just counts down monday to friday until 5:00PM and then starts again at "0" (midnight, 24 hour clock) which was all working.
Then I realized that since the time is client side (javascript) visitors on the PST timezone will see a false time compared to what they should see (the store is Eastern).
Unfortunately I can't use php or anything server side to get the time from the server, so it has to be javascript (convert to UTC and offset).
I'm doing something wrong with the variables as far as I can tell, possibly more, could someone please tell me what I'm exactly setting wrong? (it doesn't show any errors in my console).
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function calcTime(offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
offset = -5.0;
var now = utc + (3600000*offset);
function countDown() {
//var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 5) ) { // Monday to Friday only
var target = 17; // 15:00hrs is the cut-off point
if (now.getHours() < target) { // don't do anything if we're past the cut-off point
var hrs = (target - 1) - 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 = '<span id="day">00</span><span id="hour">' + pad(hrs, 2) + '</span><span id="minute">' + pad(mins, 2) + '</span><span id="second">' + pad(secs, 2) + '</span>';
document.getElementById('countdownTimer').innerHTML = str;
}
}
}
var timerRunning = setInterval('countDown()', 1000);
}
}
I see that in these lines :
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
offset = -5.0;
var now = utc + (3600000*offset);
you're creating a now variable as a number, and then in your function countDown() you're using it as a date object.
You should create your now var as a date like this
var now = new Date(utc + (3600000*offset));
I just did this to set an expires header in node.js ... here's what I did:
res.setHeader("Expires", new Date(Date.now() + 345600000).toUTCString());
for another application you could do it differently:
var updated_date = new Date(Date.now() + 345600000, //miliseconds
utc_date = updated_date.toUTCString()
Have fun!

Javascript countdown timer can't set half past hour

I'm trying to use a countdown timer to count to a certain time everyday (monday to friday). So far everything works, except it can only be set to count to a certain hour (based on the 24 hour clock) without a half hour included. So for example, if I wanted to count to 4PM, I'd set var target = 16; but if I wanted 4:30 and I tried to set var target = 1630; it doesn't work. Unfortunately I don't have much experience with javascript, but I believe the problem is either with the way it's evaluating the target time using the getHours function but not sure where to take it from there.
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown() {
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 5) ) { // Monday to Friday only
var target = 15; // 15:00hrs is the cut-off point
if (now.getHours() < target) { // don't do anything if we're past the cut-off point
var hrs = (target - 1) - 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 = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}
}
}
var timerRunning = setInterval('countDown()', 1000);
}
If you're ok with considering another method, the following javascript will count down (in seconds) to any date in the future (and count up after the date has passed).
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
var target = new Date(2014, 0, 30, 12, 30, 0, 0)
function countdown(id, targetDate){
var today = new Date()
targetDate.setDate(today.getDate())
targetDate.setFullYear(today.getFullYear())
targetDate.setMonth(today.getMonth())
var diffMillis = targetDate - today
if (diffMillis >= 0){
document.getElementById(id).innerHTML = millisToString(diffMillis)
}
}
setInterval(function(){countdown('seconds', target)},1000)
It uses the javascript date object, so you can literally use any date.
Updated example to do:
format the countdown using hours:minutes:seconds etc
stop the timer after the date is reached
Updated: updated code to override the targetDate to today's date.
Example: http://jsfiddle.net/kKx7h/5/
For 4:30PM, try var target = 16.5 instead of var target = 1630;
You now need to add another variable for the minutes. We can have target as an object literal rather than declare two variables for time:
var target={hour: 15, minute:30};
if ( (now.getHours() < target.hour) && () now.getMinutes() < target.minute ){

Categories

Resources