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);
}
}
Related
My webpage timenite.com/item-shop shows a countdown that resets every day at 5:30 AM IST, I want to make a similar page in the directory timenite.com/xx and set it to reset every week on Thursdays at 8:30 PM IST.
Below is the script of what is being used currently on the item-shop page, there were actually two script files but I have combined them into one, just in case.
Help would be appreciated, thank you.
(function ($) {
$.fn.countdown = function (options, callback) {
var settings = $.extend({
date: null,
offset: null,
day: 'Day',
days: 'Days',
hour: 'Hour',
hours: 'Hours',
minute: 'Minute',
minutes: 'Minutes',
second: 'Second',
seconds: 'Seconds'
}, options);
// Throw error if date is not set
if (!settings.date) {
$.error('Date is not defined.');
}
// Throw error if date is set incorectly
if (!Date.parse(settings.date)) {
$.error('Incorrect date format, it should look like this, 12/24/2012 12:00:00.');
}
// Save container
var container = this;
/**
* Change client's local date to match offset timezone
* #return {Object} Fixed Date object.
*/
var currentDate = function () {
// get client's current date
var date = new Date();
// turn date to utc
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
// set new Date object
var new_date = new Date(utc + (3600000*settings.offset));
return new_date;
};
/**
* Main countdown function that calculates everything
*/
function countdown () {
var target_date = new Date(settings.date), // set target date
current_date = currentDate(); // get fixed current date
// difference of dates
var difference = target_date - current_date;
// if difference is negative than it's pass the target date
if (difference < 0) {
// stop timer
clearInterval(interval);
if (callback && typeof callback === 'function') callback();
return;
}
// basic math variables
var _second = 1000,
_minute = _second * 60,
_hour = _minute * 60,
_day = _hour * 24;
// calculate dates
var days = Math.floor(difference / _day),
hours = Math.floor((difference % _day) / _hour),
minutes = Math.floor((difference % _hour) / _minute),
seconds = Math.floor((difference % _minute) / _second);
// based on the date change the refrence wording
var text_days = (days === 1) ? settings.day : settings.days,
text_hours = (hours === 1) ? settings.hour : settings.hours,
text_minutes = (minutes === 1) ? settings.minute : settings.minutes,
text_seconds = (seconds === 1) ? settings.second : settings.seconds;
// fix dates so that it will show two digets
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
// set to DOM
container.find('.days').text(days);
container.find('.hours').text(hours);
container.find('.minutes').text(minutes);
container.find('.seconds').text(seconds);
container.find('.days_text').text(text_days);
container.find('.hours_text').text(text_hours);
container.find('.minutes_text').text(text_minutes);
container.find('.seconds_text').text(text_seconds);
}
// start
var interval = setInterval(countdown, 1000);
};
})(jQuery);
$(".openNav").click(function() {
$("body").toggleClass("navOpen");
$("nav").toggleClass("open");
$(".wrapper").toggleClass("open");
$(this).toggleClass("open");
});
// Second File from here
var today = new Date();
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
var day = tomorrow.getDate();
var month = tomorrow.getMonth() + 1;
var year = tomorrow.getFullYear();
var nextday = month + '/' + day + '/' + year + ' 00:00:00';
$('#example').countdown({
date: nextday,
day: 'Day',
days: 'Days'
}, function () {
day++;
});
Update - Figured it out, thanks to a guy I met on Discord.
var curday;
var secTime;
var ticker;
function getSeconds() {
var nowDate = new Date();
var dy = 4 ; //Sunday through Saturday, 0 to 6
var countertime = new Date(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate(),20,30,0); //20 out of 24 hours = 8pm
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;
if (curday == 1) {
document.getElementById("days_text").innerHTML = "Day"
}
}
Here's my code for getting the time after adding specific time.. I don't know how to shift to tomorrow's date if the base_time is example: 4:50 PM and the 'default END TIME' is only 5:00 PM and I have to add 30 mins on the base_time. If I add 30 mins on the base, the final date/time is TOMORROW at 8:20 AM.. because the start of the day(work) is 8:00 AM.
Question : How to do this? e.g. January 3, 2016 04:50:00 PM + (00:30:00) = January 4, 2016 08:20:00 AM.
start time of work is at 8:00 AM
end is at 5:00 PM
Please help me on this. Thank you guys. I really need this.
var time = "";
var total_seconds = 0;
var total_time = 0;
// ===================================================================
function toSeconds(timeToConvert){
var hms = timeToConvert;
var a = hms.split(':');
seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
total_seconds += seconds;
}
$('#btn').click(function () {
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
if (sec <= 9) {
sec = ('0' + sec);
}
if (min <= 9) {
min = ('0' + min);
}
if (hr <= 9) {
hr = ('0' + hr);
}
var base_time = hr + ":" + min + ":" + sec;
toSeconds(base_time);
// toSeconds("16:30:00");
if ($('#acc1').is(":checked")) {
time = "00:15:00";
toSeconds(time);
}
if ($('#acc2').is(":checked")) {
time = "00:30:00";
toSeconds(time);
}
alert("total seconds = " + total_seconds);
total_time = total_seconds;
total_seconds = 0;
if (total_time <= 61200) {
var date = new Date(null);
date.setSeconds(total_time);
var date1 = day + "-" + (month+1) + "-" + year + " " + date.toISOString().substr(11, 8);
}
else {
var da = new Date();
var day1 = Number(da.toISOString().substr(8, 2)) + 1; // Date1=currentday+1
var month1 = da.getMonth();
var year1 = da.getFullYear();
total_time -= 61200;
var new_time = 28800 + total_time; // Morning 8'o clock + remaining time
da.setSeconds(total_time);
var date1 = day1 + "-" + (month1+1) + "-" + year1 + " " + da.toISOString().substr(11, 8);
}
alert(date1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label><input id="acc1" type="checkbox" name="acc">acc 1</label><br>
<label><input id="acc2" type="checkbox" name="acc">acc 2</label><br>
<input type="button" class="btn btn-success" id="btn" name="btn" value="button">
edited and modified based on #Navaneethan answer. thank for that. But no I'm curious on how to consider the weekends? Those days without work. For example, Friday, the next day should be on Monday. The same for the changes in Months. How am I supposed to do that. Please help me. Thank you.
I just modified your code... Try this. It may work
var time = "";
var total_seconds = 0;
var total_time = 0;
// ===================================================================
function toSeconds(timeToConvert) {
var hms = timeToConvert;
var a = hms.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
total_seconds += seconds;
}
$('#btn').click(function () {
var d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
if (sec <= 9) {
sec = ('0' + sec);
}
if (min <= 9) {
min = ('0' + min);
}
if (hr <= 9) {
hr = ('0' + hr);
}
var base_time = hr + ":" + min + ":" + sec;
toSeconds(base_time);
if ($('#acc1').is(":checked")) {
time = "00:15:00";
toSeconds(time);
}
if ($('#acc2').is(":checked")) {
time = "00:30:00";
toSeconds(time);
}
alert(total_seconds);
total_time = total_seconds;
total_seconds = 0;
var date = new Date();
if (total_time <= 61200) {
date.setSeconds(total_time);
var date1 = date.toISOString().substr(11, 8);
}
else {
var day1 = Number(date.toISOString().substr(8, 2)) + 1; // Date1=currentday+1
var month1 = date.getMonth();
var year1 = date.getFullYear();
total_time -= 61200;
var new_time = 28880 + total_time; //Morning 8'o clock + remaining time
date.setSeconds(total_time);
var date1 = day1 + "-" + month1 + "-" + year1 + ":" + date.toISOString().substr(11, 8);
}
alert(date1);
});
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
}
I have the following JavaScript on my site that shows the amount of time left for an order to be placed for next day delivery.
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;
};
var timerRunning = setInterval(
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;
}
}
}, 1000
);
}
The problem with this is that on saturday and sunday it just displays 00:00:00 all the time.
What I would like it to do is count the hours over a weekend as is done on this site for example: http://www.nakedwines.com/full_site
JavaScript is really not my area and I'm totally at a loss on how I can change the code to do this. Any help would be appreciated.
Fiddle is here http://jsfiddle.net/rwet0o5f/
I've moved the now.getDay() into variable and now it should be much more readable.
weekday contains 0 on Sunday, 1 on Monday and 6 on Saturday.
On Saturday we add 48 hours to the time of the deadline,
On Sunday we add only 24 hours.
http://jsfiddle.net/37ox54bk/7/
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;
};
var timerRunning = setInterval(
function countDown() {
var target = 15; // 15:00hrs is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
if(weekday == 0){//Sunday? Add 24hrs
target += 24;
}
if(weekday == 6){//It's Saturday? Add 48hrs
target += 48;
}
//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) { //stop the clock
return 0;
}
}
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;
}, 1000
);
}
Try this.
Instead of not doing anything when you are past the target time, I just increase the target time to point to a different day (the main difference is the if..else if statements at the beginning of the function)
function countDown() {
var now = new Date();
var target = 15; // 15:00hrs is the cut-off point
if (now.getDay() == 0) { // Sunday - use tomorrow's cutoff
target += 24;
} else if (now.getDay() == 6) { // Saturday - use cutoff 2 days from now
target += 48;
} else if (now.getHours() < target) { // missed the cutoff point. Use tomorrow instead
target += 24;
if (now.getDay() == 5) { // Friday - use Monday cutoff
target += 48;
}
}
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;
}, 1000);
I forked the fiddle: http://jsfiddle.net/4vhah8yt/1/
Code #sEver is good. Aj Richardson your code countdown is from new hours - is wrong.
I'd like to affter countdown hide HTML/CSS code.
Full Code: https://codepen.io/kamikstudio/pen/dyzvrQP
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;
};
var timerRunning = setInterval(
function countDown() {
var target = 14; // 15:00hrs is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
if(weekday == 0){//Sunday? Add 24hrs
target += 24;
}
if(weekday == 6){//It's Saturday? Add 48hrs
target += 48;
}
//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) { //stop the clock
return 0;
}
}
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 = '<b>' + pad(hrs, 2) + ' </b>hours<b> ' + pad(mins, 2) + ' </b>min<b> ' + pad(secs, 2) + ' </b>sec';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
}
Im creating a JS clock/date. I previously got the time to work perfectly then I decided to add more onto my clock (date). Right now I cant figure why it isn't working. If anyone could give me tip or idea how to fix it, I would greatly appreciate it.
function timedate()
{
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var dn="PM"
var d = currentTime.getDate(); <--
var day = (d < 10) ? '0' + d : d;
var m = currentTime.getMonth() + 1; <--
var month = (m < 10) ? '0' + m : m;
var yy = currentTime.getYear(); <--
var year = (yy < 1000) ? yy + 1900 : yy;
if (hours<12)
{
dn="AM"
}
if (hours>12)
{
hours=hours-12
}
if (hours==0)
{
hours=12
}
if (minutes<=9)
{
minutes="0"+minutes
}
var clocklocation = document.getElementById('timedate');
clocklocation.innerHTML = "" +hours+":"+minutes+dn+""+day + "/" + month + "/" + year;
setTimeout("timedate()", 1000);
}
timedate();
Your code works, it is just not visible because you do not have seconds showing
Also change
setTimeout("timedate()", 1000);
to
setTimeout(timedate, 1000);
because it is not recommended
and remove the <--
Make sure it runs onload or after the tag you want to show it in
Alternatively remove the line and change
timedate();
to
setInterval(timedate,1000)
const pad = num => ("0" + num).slice(-2);
const timedate = () => {
const currentTime = new Date();
let hours = currentTime.getHours();
const minutes = pad(currentTime.getMinutes());
const seconds = pad(currentTime.getSeconds());
const d = currentTime.getDate();
const day = pad(d);
const month = pad(currentTime.getMonth() + 1);
const yy = currentTime.getFullYear();
let dn = "PM"
if (hours <= 12) dn = "AM";
if (hours >= 12) hours -= 12;
if (hours == 0) hours = 12;
hours = pad(hours);
document.getElementById('timedate').innerHTML = "" +
hours + ":" +
minutes + ":" +
seconds + dn + " " +
day + "/" + month + "/" + yy;
}
window.addEventListener("load", function() {
setInterval(timedate, 1000);
});
<span id="timedate"></span>
If you set the timeout with setTimeout(timedate, 1000) instead of your current magic string version, it works1.
1 I took the liberty of adding seconds to your code as well, to make it obvious that the clock updates. Of course, you also need to remove <-- from your code.