Javascript Countdown from 8am-9pm - javascript

I have a Javascript countdown from 12am to 9pm each day and then resets itself.
I want the countdown to go from 8am-9pm instead of 12am-9pm. I have been fiddling with this but I can't seem to make it work with a start time other than the defaulted 12am.
My question is how can I make the countdown from 8-21 hours instead of 0-21 hours?
Javascript:
if (document.getElementById('countdown')) {
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() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
if (now.getHours() < target) { //
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('countdown').innerHTML = str;
}
else
$('.wereOpen').hide();
}
}
var timerRunning = setInterval('countDown()', 1000);
}
Website

I don't fully understand your question, but could you just add now.getHours() >= 7 to your if statement, i.e.
...
if (now.getHours() >= 7 && now.getHours() < target) {
...
} else {
$('.wereOpen').hide();
}
...
EDIT
In light of the comment, the following should work:
if (document.getElementById('countdown')) {
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() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
var hours = now.getHours(); //get hours
if(hours < 8 || hours >= target) {
$('.wereOpen').hide();
return;
} else
$('.wereOpen').show();
var hrs = (target - 1) - hours;
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('countdown').innerHTML = str;
}
}
var timerRunning = setInterval('countDown()', 1000);
}

Related

How to display Good Morning/Afternoon/Evening using javascript in 12hours format

It is 4:11PM here now but my output is shown as 'Good Morning' - why is this happening?
$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var h = ndate.getHours() % 12;
var format = h >= 12 ? 'PM' : 'AM';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();
if (h < 12) {
h = "0" + h;
$("h3.day-message").html("Good Morning");
} else if (h < 18) {
$("h3.day-message").html("Good Afternoon");
} else {
$("h3.day-message").html("Good Evening");
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
$('.date').html(h + ":" + m + ":" + s + format);
}
setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
The issue is because you are using the modulo operator. This means that your h > 12 check will never be hit as the remainder of the division cannot be greater than 12. It's because of this your logic always believes it's still the morning. To fix this, just use a simple < check when comparing the hour figure.
Also note that you have some issues with the formatting of the date, such as appending extra zeroes so you end up with 011 as hour values. You can fix this by using slice().
With all that said, try this:
$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var hours = ndate.getHours();
var message = hours < 12 ? 'Good Morning' : hours < 18 ? 'Good Afternoon' : 'Good Evening';
$("h3.day-message").text(message);
$('.date').html(hours.leadingZeroes(2) + ":" + ndate.getMinutes().leadingZeroes(2) + ":" + ndate.getSeconds().leadingZeroes(2) + (hours < 12 ? 'AM' : 'PM'));
}
setInterval(dateTime, 1000);
});
Number.prototype.leadingZeroes = function(len) {
return (new Array(len).fill('0', 0).join('') + this).slice(-Math.abs(len));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
$(document).ready(function() {
function dateTime() {
var format="";
var ndate = new Date();
var hr = ndate.getHours();
var h = hr % 12;
if (hr < 12)
{
greet = 'Good Morning';
format='AM';
}
else if (hr >= 12 && hr <= 17)
{
greet = 'Good Afternoon';
format='PM';
}
else if (hr >= 17 && hr <= 24)
greet = 'Good Evening';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();
if (h < 12) {
h = "0" + h;
$("h3.day-message").html(greet);
} else if (h < 18) {
$("h3.day-message").html(greet);
} else {
$("h3.day-message").html(greet);
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
$('.date').html(h + ":" + m + ":" + s + format);
}
setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
You are calculating mode, so h will never be greater that 12
So, Instead of
var h = ndate.getHours() % 12;
Use it
var h = ndate.getHours();
Explaination: modulo operator(%) will divide total hours by 12 and return the Remainder.
For example if current time is 4 pm, I'll be 16 hours, so It'll return 4
Without jQuery
const messages = [
{ ampm: "am", "greet": 'Good Morning' },
{ ampm: "pm", "greet": 'Good Afternoon' },
{ ampm: "pm", "greet": 'Good Evening' }
];
window.addEventListener("DOMContentLoaded", () => {
const dateSpan = document.getElementById("date");
const message = document.getElementById("day-message");
const dateTime = () => {
let now = new Date(),
hour = now.getHours(),
hh = hour % 12, // (hour % 12).toString().padStart(2,"0") if you want leading 0
mm = now.getMinutes().toString().padStart(2,"0"),
ss = now.getSeconds(),
period = 0;
if (hour < 12) period = 0;
else if (hour >= 12 && hour < 17) period = 1;
else if (hour >= 17 && hour <= 24) period = 2;
message.textContent = messages[period].greet;
dateSpan.textContent = `${hh}:${mm}${messages[period].ampm}`;
};
setInterval(dateTime, 500);
});
<h3 id="day-message"></h3>
<span id="date"></span>
Display Good Morning/Afternoon/Evening using javascript in 12hours format
const displayGreeting =()=>{
const myDate = new Date();
const hrs = myDate.getHours();
let greet;
if (hrs < 12)
greet = 'Good Morning';
else if (hrs >= 12 && hrs <= 17)
greet = 'Good Afternoon';
else if (hrs >= 17 && hrs <= 24)
greet = 'Good Evening';
return greet
}

Format time algorithm

I am really struggling to solve human readable duration format algorithm. I have solved the most of it, but there are some mistakes anyway which I cannot solve for a while. Some tests pass, while others don't. Please help me it solve it.
The code
function formatDuration (seconds) {
// Complete this function
var minutes = Math.round(seconds / 60);
var thisSeconds = Math.round(seconds % 60);
var hours = Math.round(seconds / 3600);
var days = Math.round(seconds / 86400);
var years = Math.round(seconds / 31536000);
var stringYear = "year";
var stringDay = "day";
var stringHour = "hour";
var stringMinute = "minute";
var stringSecond = "second";
if (years > 1) {
stringYear = "years";
} else if (days > 1) {
stringDay = "days";
} else if (hours > 1) {
stringHour = "hours";
} else if (thisSeconds > 1) {
stringSecond = "seconds";
} else if (minutes > 1) {
stringMinute = "minutes";
}
if (minutes >= 60) {
hours = Math.round(minutes/60);
minutes = Math.abs(minutes - hours*60);
if (minutes > 1) {
stringMinute = "minutes";
}
}
if (hours >= 24) {
days = Math.round(hours/24);
if (days > 1) {
stringDay = "days";
}
hours = hours - days*24;
stringHour = "hours";
}
if (days > 365) {
days = Math.abs(days - years*365);
stringDay = "days";
}
var obj = new Map();
obj.set(stringYear, years);
obj.set(stringDay, days);
obj.set(stringHour, hours);
obj.set(stringMinute, minutes);
obj.set(stringSecond, thisSeconds);
var empArr = [];
obj.forEach(function (value, key, mapObj) {
if (value == 0) {
obj.delete(key);
}
var res = value + " " + key;
if (value > 0) {
empArr.push(res);
formatStrings(empArr);
}
});
return formatStrings(empArr);
}
function formatStrings(arr) {
return arr.length == 1 ? arr[0] : arr.slice(0, arr.length - 1).join(", ") + " and " + arr[arr.length - 1];
//console.log(str);
}
formatDuration(3600);
Test results
Math.round performs rounding (rounding up if the value would be above .5).
use Math.floor everywhere to take the truncated part.
I would also use modulo to avoid all the complicated logic you've added.
So
var minutes = Math.round(seconds / 60);
would become
var minutes = Math.floor(seconds / 60) % 60;
and so on.

JavaScript set future date as today

I have the below script in our website which generates a countdown timer. The dateFuture is set to todays date at midnight. Is it possible to set this as the current date so that we don't have to change this every day?
Thank you.
var today = new Date();
dateFuture = new Date(2016, 11, 16, 23, 59, 59);
function GetCount() {
dateNow = new Date();
amount = dateFuture.getTime() - dateNow.getTime();
delete dateNow;
if(amount < 0) {
document.getElementById("countbox").innerHTML = "Now!";
} else {
days = 0;
hours = 0;
mins = 0;
secs = 0;
out = "";
amount = Math.floor(amount / 1000);
days=Math.floor(amount / 86400);
amount = amount % 86400;
hours = Math.floor(amount / 3600);
amount = amount % 3600;
mins = Math.floor(amount / 60);
amount = amount % 60;
secs = Math.floor(amount);
if(days != 0) {
out += days + " day" + ((days != 1) ? "s" : "") + ", ";
}
if(days != 0 || hours != 0) {
out += hours + " hour" + ((hours != 1) ? "s" : "") + ", ";
}
if(days != 0 || hours != 0 || mins != 0) {
out += mins + " minute" + ((mins != 1) ? "s" : "") + ", ";
}
out += secs + " seconds";
document.getElementById("countbox").innerHTML = out;
setTimeout("GetCount()", 1000);
}
}
window.onload = function() { GetCount(); }
<div id="countbox"></div>
You can manipulate the date by using setHours, setMinutes, setSeconds and setMilliseconds.
var dateFuture = new Date();
dateFuture.setHours(23);
dateFuture.setMinutes(59);
dateFuture.setSeconds(59);
dateFuture.setMilliseconds(999);

Javascript Countdown to show/hide on specified days & hours

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>

Simple countdown timer

I want to create a simple countdown timer, I found something its working only for seconds, I want to add hours:minutes:seconds...
how can I make the same timer for hh:mm:ss
<script type="text/javascript">
var seconds;
var temp;
function countdown() {
seconds = document.getElementById('countdown').innerHTML;
seconds = parseInt(seconds, 10);
if (seconds == 1) {
temp = document.getElementById('countdown');
temp.innerHTML = "00";
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = seconds;
timeoutMyOswego = setTimeout(countdown, 1000);
}
countdown();
</script>
var seconds;
var temp;
function countdown() {
time = document.getElementById('countdown').innerHTML;
timeArray = time.split(':')
seconds = timeToSeconds(timeArray);
if (seconds == '') {
temp = document.getElementById('countdown');
temp.innerHTML = "00:00:00";
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = secondsToTime(seconds);
timeoutMyOswego = setTimeout(countdown, 1000);
}
function timeToSeconds(timeArray) {
var minutes = (timeArray[0] * 60) + (timeArray[1] * 1);
var seconds = (minutes * 60) + (timeArray[2] * 1);
return seconds;
}
function secondsToTime(secs) {
var hours = Math.floor(secs / (60 * 60));
hours = hours < 10 ? '0' + hours : hours;
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
minutes = minutes < 10 ? '0' + minutes : minutes;
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
seconds = seconds < 10 ? '0' + seconds : seconds;
return hours + ':' + minutes + ':' + seconds;
}
countdown();
<div id="countdown">01:02:15</div>
You may have different variables and different inner html's for the each part of your timer as hours for "hh", minutes for "mm" and seconds for "ss".. and for every step set the inner htmls equal to variables.
Initialize hours with some number and make it countdown by 1 when the others are zero and at the same time make the minutes and seconds equal to 59 and start counting down the seconds as the code you added above, then same thing goes for the minutes-seconds relation (when seconds are zero and minutes are not zero countdown minutes by one). At the end return if all the variables are zero..
Hope this helps..
You didn't say if you want to count up or down so here is a solution for both, just take the parts of the code you need:
(Fiddle: http://jsfiddle.net/Luc4oqo8/2/)
(I used jQuery here, you should use it too because its awesome)
HTML:
<div id="counter_up">
<p id="h">00</p>:<p id="m">00</p>:<p id="s">00</p>
</div>
<div id="counter_dn">
<p id="h">00</p>:<p id="m">00</p>:<p id="s">00</p>
</div>
JS:
var h_up = GetElementInsideContainer ("counter_up", "h");
var m_up = GetElementInsideContainer ("counter_up", "m");
var s_up = GetElementInsideContainer ("counter_up", "s");
var h_dn = GetElementInsideContainer ("counter_dn", "h");
var m_dn = GetElementInsideContainer ("counter_dn", "m");
var s_dn = GetElementInsideContainer ("counter_dn", "s");
// THIS COUNTS UP
setInterval ( function()
{
if (parseInt(s_up.innerHTML) < 59)
{
s_up.innerHTML = parseInt(s_up.innerHTML) + 1;
if (parseInt(s_up.innerHTML) < 10)
s_up.innerHTML = "0" + s_up.innerHTML;
}
else
{
s_up.innerHTML = 0;
if (parseInt(m_up.innerHTML) < 59)
{
m_up.innerHTML = parseInt(m_up.innerHTML) + 1;
if (parseInt(m_up.innerHTML) < 10)
m_up.innerHTML = "0" + m_up.innerHTML;
}
else
{
m_up.innerHTML = 0;
if (parseInt (h_up.innerHTML) < 23)
{
h_up.innerHTML = parseInt(h_up.innerHTML) + 1;
if (parseInt(h_up.innerHTML) < 10)
h_up.innerHTML = "0" + h_up.innerHTML;
}
else
{
h_up.innerHTML = m_up.innherHTML = s_up.innerHTML = 0;
}
};
}
}, 1000);
// THIS COUNTS DOWN
setInterval ( function()
{
if (parseInt(s_dn.innerHTML) > 0)
{
s_dn.innerHTML = parseInt(s_dn.innerHTML) - 1;
if (parseInt(s_dn.innerHTML) < 10)
s_dn.innerHTML = "0" + s_dn.innerHTML;
}
else
{
s_dn.innerHTML = 59;
if (parseInt(m_dn.innerHTML) > 0)
{
m_dn.innerHTML = parseInt(m_dn.innerHTML) - 1;
if (parseInt(m_dn.innerHTML) < 10)
m_dn.innerHTML = "0" + m_dn.innerHTML;
}
else
{
m_dn.innerHTML = 59;
if (parseInt (h_dn.innerHTML) > 0)
{
h_dn.innerHTML = parseInt(h_dn.innerHTML) - 1;
if (parseInt(h_dn.innerHTML) < 10)
h_dn.innerHTML = "0" + h_dn.innerHTML;
}
else
{
h_dn.innerHTML = 23;
m_dn.innherHTML = s_dn.innerHTML = 59;
}
};
}
}, 1000);
// Very useful, got it from here: http://stackoverflow.com/questions/7171483/simple-way-to-get-element-by-id-within-a-div-tag
function GetElementInsideContainer(containerID, childID)
{
var elm = {};
var elms = document.getElementById(containerID).getElementsByTagName("*");
for (var i = 0; i < elms.length; i++)
{
if (elms[i].id === childID)
{
elm = elms[i];
break;
}
}
return elm;
}
CSS:
p
{
display: inline-block;
}
if you have Seconds get hours and minutes as follow
var hours = parseInt( Your seconds here / 3600 ) % 24;
var minutes = parseInt( Your seconds here / 60 ) % 60;
var seconds = Your seconds here % 60;
here your complete time in HH:MM:SS
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
Sort and sweet approach

Categories