Check if time is within time bounds with minutes - javascript

looking for help in changing the working hours from 8 to 5 to 8:30 to 5:30. would appreciate some help with amending the existing JavaScript function:
<html>
<head>
<script>
onload = function ( )
{
var now = new Date();
var weekday = now. getDay();
var hours = now.getHours();
if ((hours >= 8) && (hours <= 5)) && ((weekday >=1) && (weekday <= 5))
{
document.getElementById("status").src="open.png";
}
else
{
document.getElementById("status").src="closed.png";
}
}
</script>
</head>
<body>
<img id="status" src="">
</body>
</html>

Since .getHours() returns an integer, check the hour and the minutes accordingly using .getMinutes().
It's a bit messy, but it's easy to understand. I've broken it down below the snippet.
const cur = new Date();
const minutes = cur.getMinutes();
const h = cur.getHours();
const d = cur.getDay();
let closed = true;
if ((d >= 1) && (d <= 5)) {
if (h > 8 && h < 17) {
if (h == 8 && minutes < 30 || h == 17 && minutes > 30) {
closed = true;
} else {
closed = false;
}
} else {
closed = true;
}
} else {
closed = true;
}
console.log("Closed? : " + closed);
(d >= 1) && (d <= 5) - this checks whether the weekday is within the bounds of Monday (1) and Friday (5)
(h > 8 && h < 17) - is the current hour within the bounds 8 AM and 5 PM (8 and 17 respectively)?
h == 8 && minutes < 30 || h == 17 && minutes > 30 - if the current hour is 8, check if the minutes is smaller than 30. We need to ensure that the minutes is 30 or greater (8:30+). If the current hour is 5, check if the minutes is greater than 30. We need to ensure that the minutes is 30 or less (5:30-). If any of these are satified, we know it is closed.
Here's a comprehensive snippet with logs:
const cur = new Date();
const minutes = cur.getMinutes();
const h = cur.getHours();
const d = cur.getDay();
let closed = true;
if ((d >= 1) && (d <= 5)) {
console.log("Weekday is within Monday and Friday? check");
if (h > 8 && h < 17) {
console.log("Hour is between 8 AM and 5PM? check");
if (h == 8 && minutes < 30 || h == 17 && minutes > 30) {
console.log("Minutes is more then 30 if hour is 8 or minutes is less than 30 if hour is 15? fail");
closed = true;
} else {
console.log("Minutes is more then 30 if hour is 8 or minutes is less than 30 if hour is 15? check");
closed = false;
}
} else {
console.log("Hour is between 8 AM and 5PM? fail");
closed = true;
}
} else {
console.log("Weekday is within Monday and Friday? fail");
closed = true;
}
console.log("Closed? : " + closed);
Here's what it should look like in your particular example:
<html>
<head>
<script>
onload = function() {
const cur = new Date();
const minutes = cur.getMinutes();
const h = cur.getHours();
const d = cur.getDay();
let closed = true;
if ((d >= 1) && (d <= 5)) {
if (h > 8 && h < 17) {
if (h == 8 && minutes < 30 || h == 17 && minutes > 30) {
closed = true;
} else {
closed = false;
}
} else {
closed = true;
}
} else {
closed = true;
}
if (closed) {
document.getElementById("status").src = "closed.png";
} else {
document.getElementById("status").src = "open.png";
}
}
</script>
</head>
<body>
<img id="status" src="">
</body>
</html>

first of all, you mistakenly added extra bracket in your if expression:
if ((hours >= 8) && (hours <= 5)) && ((weekday >=1) && (weekday <= 5))
I ecountered this seemingly easy to solve in past, until you need to compare the minutes inbetween, you will run to unecessary complex logic.
the cleanest way to solve this is convert into "seconds from midnight" which makes easier for comparison between two time. (this technique similar to UNIX TIME technique use by lots of date system nowdays, you can google it)
in smaller project its ok to do following:
var now = new Date();
var weekday = now.getDay();
function getSecond(hours, minutes){
return ( (hours * 60 * 60) + (minutes * 60) ); //this will return the total seconds past midnight
}
//converting to seconds to certain point of time is used by "timestamp" technique, you can google bout it
let openSeconds = getSecond(8,30);
let closeSeconds = getSecond(17,30);
let nowSeconds = getSecond( now.getHours(), now.getMinutes());
console.log(openSeconds + ' ' + closeSeconds + ' ' + nowSeconds);
if( (weekday >= 1) && (weekday <= 5) ){ //Weekday validation
if(openSeconds < nowSeconds && nowSeconds <= closeSeconds){ //inclusive, ( < or <= ) you decide
document.getElementById("status").src = "open.png";
}else{
document.getElementById("status").src = "closed.png";
}
}
in bigger project, i always always recommend to use dayjs or moment js to deal with timezones like explained in video:
https://www.youtube.com/watch?v=-5wpm-gesOY

Adapting the code you posted:
window.onload = function () {
var now = new Date();
var weekday = now.getDay();
var hours = now.getHours();
var minutes = now.getMinutes();
var status = document.getElementById('status');
// if Monday - Friday
if (weekday >= 1 && weekday <= 5) {
// if before 8am OR after 5pm
if (hours < 8 || hours > 17) {
status.src = 'closed.png';
}
// if less than 30 minutes past 8am, OR
// if 30+ minutes past 5pm
else if (minutes < 30 && hours === 8 || minutes >= 30 && hours === 17) {
status.src = 'closed.png';
}
// if 30 or more minutes past any hour between 8am and 4pm,
// or up to 29 minutes past 5pm, you're open!
else {
status.src = 'open.png';
}
}
};

Related

JavaScript if/else statements are altering variables used as conditions in the same statements

I have a Piece of code that's supposed to change the text displayed according to the current day of the week and the time of day.
For some reason the if/else statements I'm using to check variables are altering the day variable. The end value changes from day do day and removing sections of if else statements also change the result.
I plan on embedding this on a WordPress site using the HTML block
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Buttons</h2>
<p id="demo"></p>
<button id="q">Q</button>
<button id="w">W</button>
<button id="e">E</button>
<button id="r">R</button>
<button id="t">T</button>
<button id="y">Y</button>
<div id="myDIVq">
This is my DIVq element.
</div>
<div id="myDIVw" style="display:none">
This is my DIVw element This space will be used for our weekday schedule.
</div>
<div id="myDIVe" style="display:none">
This is my DIVe element This space will be used for our weekend schedule.
</div>
<div id="myDIVr" style="display:none">
This is my DIVr element This space will be used for our presenters page.
</div>
<div id="myDIVt" style="display:none">
This is my DIVt element.
</div>
<div id="myDIVy" style="display:none">
This is my DIVy element.
</div>
<script>
//EFM Page Content management V2.0
//When Corresponding Button is clicked oly the relevent content will be displayed
// using spread syntax to convert collection to array
// forEach is an array method
[...document.getElementsByTagName("button")].forEach(function(item) {
// adding eventListener to the elements
item.addEventListener('click', function() {
// calling the methods
// this.id will be the id of the clicked button
// there is a method in the object by same name, which will be trigger
obj[this.id]();
})
})
var x1 = document.getElementById("myDIVq")
var x2 = document.getElementById("myDIVw")
var x3 = document.getElementById("myDIVe")
var x4 = document.getElementById("myDIVr")
var x5 = document.getElementById("myDIVt")
var x6 = document.getElementById("myDIVy");
var obj = {
q: function() {
HideAll()
x1.style.display = "block"
},
w: function() {
HideAll()
x2.style.display = "block"
},
e: function() {
HideAll()
x3.style.display = "block"
},
r: function() {
HideAll()
x4.style.display = "block"
},
t: function() {
HideAll()
x5.style.display = "block"
},
y: function() {
HideAll()
x6.style.display = "block"
}
}
function HideAll() {
x1.style.display = "none"
x2.style.display = "none"
x3.style.display = "none"
x4.style.display = "none"
x5.style.display = "none"
x6.style.display = "none"
}
//Initailize Date and Time
Time = new Date()
let day = Time.getDay()
let hour = Time.getHours()
//Show is a Test variable
let show;
//Everyday Shows
if (3 <= hour && hour < 4) {
show = "Gospel";
//6 to 9 Show (All Weekdays)
//Sunday Shows
} else if ((day = 0) && (4 <= hour && hour < 5)) {
show = "Gospel";
//6 to 7 Show (Sundays)
} else if ((day = 0) && (5 <= hour && hour < 6)) {
show = "Sermon";
//7 to 8 Show (Sundays)
} else if ((day = 0) && (6 <= hour && hour < 9)) {
show = "Sunday Breakfast with Leonie";
//8 to 11 Show (Sundays)
} else if ((day = 0) && (9 <= hour && hour < 12)) {
show = "Lovers Corner";
//11 to 14 Show (Sundays)
} else if ((day = 0) && (12 <= hour && hour < 15)) {
show = "Country With Dewald";
//6 to 9 Show (Sundays)
} else if ((day = 0) && (15 <= hour && hour < 17)) {
show = "T-Junction with Manie";
//17 to 19 Show (Sundays)
} else if ((day = 0) && (17 <= hour && hour < 20)) {
show = "Jou Keuse with Sol";
//19 to 22 Show (Sundays)
//Weekday Shows
} else if ((1 <= day && day < 6) && (4 <= hour && hour < 7)) {
show = "PS Show";
//6 to 9 Show (All Weekdays)
} else if ((1 <= day && day < 6) && (7 <= hour && hour < 10)) {
show = "Daylight With Dewald";
//9 to 12 Show (All Weekdays)
} else if ((1 <= day && day < 6) && (10 <= hour && hour < 13)) {
show = "Weekly View";
//12 to 15 Show (All Weekdays)
} else if ((1 <= day && day < 6) && (13 <= hour && hour < 16)) {
show = "Sunset Drive";
//15 to 18 Show (All Weekdays)
} else if ((day = 3) && (16 <= hour && hour < 17)) {
show = "Live Well";
//18 to 19 Show (Wednesdays)
} else if ((day = 4) && (16 <= hour && hour < 17)) {
show = "Trends";
//18 to 19 Show (Thursdays)
} else if ((1 <= day && day <= 4) && (17 <= hour && hour < 20)) {
show = "Jono Mich Monday to Thursday";
//19 to 22 Show (Monday to Thursday)
} else if ((day = 5) && (17 <= hour && hour < 20)) {
show = "Fryday Jol";
//19 to 22 Show (Friday)
//Saturday Shows
} else if ((6 <= day) && (4 <= hour && hour < 7)) {
show = "Weekend Buzz with Sam";
//6 to 9 Show (Saterday)
} else if ((6 <= day) && (7 <= hour && hour < 10)) {
show = "Saterday Shakeup with Sol";
//9 to 12 Show (Saterday)
} else if ((6 <= day) && (10 <= hour && hour < 14)) {
show = "Top 40 With Thabiso";
//12 to 16 Show (Saterday)
} else if ((6 <= day) && (14 <= hour && hour < 16)) {
show = "Drive Time With Laurette";
//16 to 18 Show (Saterday)
} else if ((6 <= day) && (16 <= hour && hour <= 19)) {
show = "Rock show With Kelly";
//18 to 21 Show (Saterday)
//If there are now shows
} else {
show = "Music";
}
//Changes demo div to display active show, test
document.getElementById("myDIVq").innerHTML = show;
document.getElementById("myDIVy").innerHTML = day + " " + hour;
//if (500 < size && size < 600) { doStuff(); }
</script>
</body>
</html>
This is happening because you are assigning the value in the if check. instead of assigning it using =, use == or === to check for equality
if (day = 0) // incorrect
if (day == 0) // correct

Troubleshooting JS Shipping Countdown Timer

Is you'll probably be able to tell I'm a complete JS rookie but I've spent my day working on this code to display a shipping timer, compiled from bits of various other posts on SO (thanks!).
It seemed to be going well until I completed adding all the functionality I needed and now it's not working. When you first run the snippet it works correctly but as soon as it ticks the "day" value displays incorrectly (it should display 'tomorrow' but it switches to 'today') and the timer itself has stopped counting down.
I can't figure out for the life of me where I messed it up so looking for some assistance if possible! Thanks in advance.
JSFiddle: http://jsfiddle.net/c3otusv6/
(function() {
var start = new Date();
start.setHours(14, 0, 0);
var maybePluralize = function maybePluralize(count, noun) {
var suffix = arguments.length <= 2 || arguments[2] === undefined ? 's' : arguments[2];
return count + ' ' + noun + (count !== 1 ? suffix : '');
};
var now = new Date();
var day = now.getDay();
function tick() {
if (day >= 1 && day <= 5 && now < start) {
document.getElementById('ddate').innerHTML = 'today';
} else if (day >= 1 && day <= 4 && now >= start || day == 7) {
document.getElementById('ddate').innerHTML = 'tomorrow';
} else if (day == 5 && now >= start || day == 6) {
document.getElementById('ddate').innerHTML = 'Monday';
}
if (day == 6 || day == 5 && now > start || day == 7 && now < start) {
document.getElementById('countdown').innerHTML = "now";
} else {
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = (start - now) / 1000;
var hh = Math.floor(remain / 60 / 60 % 60);
var mm = Math.floor(remain / 60 % 60);
document.getElementById('countdown').innerHTML = "in the next <strong>" + maybePluralize(hh, 'hour') + " " + maybePluralize(mm, 'min') + "</strong>";
setTimeout(tick, 1000);
}
}
document.addEventListener('DOMContentLoaded', tick);
})();
If you need to have the function called every second, you need to use setInterval. setTimeout just runs the given function once after the specified number of seconds.
I have made small edit to you fiddle, to make it run every second.
As for the "day" value being incorrect, I think you need to check your if statements. I quite dont understand your business logic.
Also note - Sunday is given by '0' in getDay. And I see you using day == 7, so you might want to check that and do the necessary adjustments. I guess you need to -1 from all your if statements for day.
http://jsfiddle.net/wm9kj8yb/
(function() {
var start = new Date();
var now = new Date();
var day = now.getDay();
start.setHours(14, 0, 0);
function maybePluralize(count, noun) {
var suffix = arguments.length <= 2 || arguments[2] === undefined ? 's' : arguments[2];
return count + ' ' + noun + (count !== 1 ? suffix : '');
};
function tick() {
now = new Date();
day = now.getDay();
if (day >= 1 && day <= 5 && now < start) {
document.getElementById('ddate').innerHTML = 'today';
} else if (day >= 1 && day <= 4 && now >= start || day == 7) {
document.getElementById('ddate').innerHTML = 'tomorrow';
} else if (day == 5 && now >= start || day == 6) {
document.getElementById('ddate').innerHTML = 'Monday';
}
if (day == 6 || day == 5 && now > start || day == 7 && now < start) {
document.getElementById('countdown').innerHTML = "now";
} else {
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = (start - now) / 1000;
var ss = Math.floor(remain % 60);
remain = Math.floor(remain / 60);
var mm = remain % 60;
remain = Math.floor(remain / 60);
var hh = remain % 60;
document.getElementById('countdown').innerHTML = "in the next <strong>" + maybePluralize(hh, 'hour') + " " + maybePluralize(mm, 'min') + " " + " " + maybePluralize(ss, 'sec') + "</strong>";
}
}
document.addEventListener('DOMContentLoaded', function() {
setInterval(tick, 1000);
});
})();
Order <span id='countdown'></span> for dispatch <span id='ddate'></span>

Check if time is between two values with hours and minutes in javascript

I need to check if a time is between a start and end time. All times are on the same day, so date is not important. I'm able to compare hours, but I'm unsure how to add in minutes to the start and end times.
var thedate = new Date();
var dayofweek = thedate.getUTCDay();
var hourofday = thedate.getUTCHours();
var minutesofday = date.getMinutes();
function inTime() { if (dayofweek != 0 && dayofweek != 7 && (hourofday > 13 && hourofday < 20)) { return true; } return false; }
If I want to check whether the time is between 13:05 and 19:57, how would I add the minutes to my inTime function? If I add them to the if statement, it fails to work:
function inTime() { if (dayofweek != 0 && dayofweek != 7 && ((hourofday > 13 && minutesofday > 5) && (hourofday < 20 && minutesofday < 57))) { return true; } return false; }
If its 14:04 your condition will fail as 4 is smaller 5. The simplest would probably be to just take the full minutes of the day:
const start = 13 * 60 + 5;
const end = 19 * 60 + 57;
const date = new Date();
const now = date.getHours() * 60 + date.getMinutes();
if(start <= now && now <= end)
alert("in time");
If you're saying you want to check if the time "now" is between two times, you can express those times as minutes-since-midnight (hours * 60 + minutes), and the check is quite straightforward.
For instance, is it between 8:30 a.m. (inclusive) and 5:00 p.m. (exclusive):
var start = 8 * 60 + 30;
var end = 17 * 60 + 0;
function inTime() {
var now = new Date();
var time = now.getHours() * 60 + now.getMinutes();
return time >= start && time < end;
}
console.log(inTime());
The above uses local time; if you want to check UTC instead, just use the equivalent UTC methods.
Convert times to milliseconds and then you can compare easily.
short version:
if(timeToCheck.getTime() >= startTime.getTime() &&
timeToCheck.getTime() <= endTime.getTime()) {
// ...
}
OR:
let startTimeMilli = startTime.getTime();
let endTimeMilli = endTime.getTime();
let timeToCheckMilli = timeToCheck.getTime();
// change >= to > or <= to < as you need
if (timeToCheckMilli >= startTimeMilli && timeToCheckMilli <= endTimeMilli) {
// do your things
}

Time/hours syntax in JavaScript - how to do times that aren't on the hour

I'm using jQuery to show a different message depending on whether the business I work for is open or not. Since the business only opens at 9.30, I need to be able to write this into the jQuery but so far I've only been able to google things that specify times on the hour.
var thehours = new Date().getHours();
var themessage;
var open = ('nu open');
var gesloten = ('nu gesloten');
if (thehours >= 9.30 && thehours < 18) {
themessage = open;
} else if (thehours >= 18 && thehours < 24) {
themessage = gesloten;
} else if (thehours >= 0 && thehours < 9.30) {
themessage = gesloten;
}
$('.bericht').append(themessage);
var thehours1 = new Date().getHours();
var themessage1;
var open1 = ('09.30 - 18.00');
var gesloten1 = ('18.00 - 09.30');
if (thehours1 >= 9.30 && thehours1 < 18) {
themessage1 = open1;
} else if (thehours1 >= 18 && thehours1 < 24) {
themessage1 = gesloten1;
} else if (thehours1 >= 0 && thehours1 < 9.30) {
themessage1 = gesloten1;
}
$('.bericht1').append(themessage1);
These are two different messages that show either 'now open/now closed' and either the opening or closing times.
It works but only seems to show that's we're open between 10.00 and 18.00, not 9.30 and 18.00, so I wonder if the syntax on 9.30 is wrong.
A quick look at the docs for getHours would tell you that it returns the
... integer number, between 0 and 23, representing the hour for the given date according to local time.
So using 9.30 will never work (and if it did, you're using decimal numbers to represent that time - wouldn't it be 9.5?!)
So you need hours and minutes:
var date = new Date();
var hrs = date.getHours();
var mins = date.getMinutes();
if((hrs==9 && mins>30) || hrs >=10){
console.log("Its past 930am")
}
Putting this together with the rest of your logic gives:
function areWeOpen(){
var date = new Date();
var hrs = date.getHours();
var mins = date.getMinutes();
if(((hrs==9 && mins>30) || hrs >=10) && hrs<18){
return true;
}
return false;
}
console.log( areWeOpen() ? "We are open" : "We are closed");
Simple!
9.30 is a floating-point number (i.e. 9 and 3 tenths), not hours and minutes in your code.
Since getHours() returns integer number of full hours, your code will act similar to:
if (thehours1 >= 10 && thehours1 < 18) {
themessage1 = open1;
} else if (thehours1 >= 18 && thehours1 < 24) {
themessage1 = gesloten1;
} else if (thehours1 >= 0 && thehours1 < 9) {
themessage1 = gesloten1;
}
which will return unexpected results for time 09:00 - 10:00.
You need to manually check hours and minutes.
Something like this:
var thehours = new Date().getHours();
var theminutes = new Date().getMinutes();
var themessage;
var open = ('nu open');
var gesloten = ('nu gesloten');
if (thehours === 9 && theminutes >= 30) { // 09:30 - 10:00 open
themessage = open;
} else if (thehours >= 10 && thehours < 18) { // 10:00 - 18:00 open
themessage = open;
} else { // when we are not open - we are closed :)
themessage = gesloten;
}
$('.bericht').append(themessage);
You don't need to create conditions for non-working hours, you can just find working hours, and use else for non-working.
As alternative, you can use some sort of "minute of day" term since it is easier to compare them:
function getMinuteOfDay(hour, minute)
{
return hour * 60 + minute;
}
var now = new Date();
var nowMinuteOfDay = getMinuteOfDay(now.getHours(), now.getMinutes());
var isOpen = nowMinuteOfDay >= getMinuteOfDay(9, 30) && nowMinuteOfDay <= getMinuteOfDay(18, 00);
themessage1 = isOpen ? open1 : gesloten1;

Javascript time between 08:30 - 20:00

I am trying to make a message show between certain time ranges in a day but i cant make it work it either shows the first IF or doesnt show anything at all with an error i cant seem to figure out. what am i doing wrong?
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();
if(today.getDay() == 4){
if(hour > 8 && minute > 30 || hour < 20){
document.getElementById('test').innerHTML = ('come today till 20:00');
} else if (hour > 20 && hour < 0){
document.getElementById('test').innerHTML = ('Come tomorrow till 20:00');
} else (hour > 0 && hour < 8).document.getElementById('test').innerHTML = ('Come today from 08:00 till 20:00');
}
figured it out thanks for the help guys :)
this is how it works now.
if(today.getDay() == 4){
if((hour === 8 && minute > 30 || hour > 8) && hour < 20){
document.getElementById('test').innerHTML = ('Kom vandaag langs in onze showtuin tot 20:00 uur donderdag');
} else if (hour >= 20 && hour < 24){
document.getElementById('test').innerHTML = ('Kom morgen langs in onze showtuin tot 20:00 uur');
} else{
document.getElementById('test').innerHTML = ('Kom vandaag langs in onze showtuin van 08:00 tot 20:00 donderdag');
}
}
You could simplify the conditions a bit, with checking from small values to greater values, like
if (today.getDay() == 4) {
if (hour < 8) {
document.getElementById('test').innerHTML = 'Come today from 08:00 till 20:00';
} else if (hour < 20) {
document.getElementById('test').innerHTML = 'Come today till 20:00';
} else if (hour < 24) {
document.getElementById('test').innerHTML = 'Come tomorrow till 20:00';
}
}
Working with absolute minute may become simplier:
var today = new Date();
var crtminut = ((today/60000).toFixed(0)-today.getTimezoneOffset())%1440;
var minmin = 8*60+30;
var minmax = 20*60;
if (today.getDay() == 4) {
if ((minmin <= crtminut) && (crtminut < minmax)) {
... inner period
} else {
... outer period
}
}
Each if can use the previous condition to its advantage which means if you correctly sort the conditions you can make it really simple:
if (hour >= 20) {
//20:00 - 23:59
}
else if (hour > 8) {
//9:00 - 19:59
}
else if (hour == 8 && minute >= 30) {
//8:30 - 8:59
}
else {
//0:00 - 8:29
}

Categories

Resources