I am not a javascript coder, but I need to modify this code so that I can have a status bar shown for multiple times during the week. How can I add to this statement to cover another day of the week or other times on Sunday? I need to have the bar show up Sunday from 5pm to 7pm and Thursday between 7p and 9p. Just wondered how I could modify this to work. Can someone help?
var d = new Date();
var Day = d.getDay();
var Time = d.getHours();
if (d.getDay() == 0 && d.getHours() >= 9 && d.getHours() <= 12) {
jQuery(".streaming").show();
} else {
jQuery(".streaming").hide();
}
First of all, you must understand how the Date's instance methods that you are using works. You can try it here getDay, and here getHours.
So, you code goes to something like:
var date = new Date();
var day = date.getDay();
var hour = date.getHours();
if ((day == 0 && hour >= 17 && hour <= 19) ||
(day == 5 && hour >= 19 && hour <= 21)) {
jQuery(".streaming").show();
} else {
jQuery(".streaming").hide();
}
You should take a look at the OR (||) operator in JavaScript too.
Thanks for the help. Based on your help I have modified it and also added a specific minute as well. Is this a proper way to do this or should I not be using get.Minutes?
var date = new Date();
var day = date.getDay();
var hour = date.getHours();
var minute = date.getMinutes();
if ((day == 0 && hour >= 08 && minute >= 50 && hour <= 12) ||
(day == 0 && hour >= 16 && minute >= 50 && hour <= 19) ||
(day == 5 && hour >= 18 && minute >= 50 && hour <= 21)) {
jQuery(".streaming").show();
} else {
jQuery(".streaming").hide();
}
I would suggest you to refactor like this
if (showForDay(d)) {
jQuery(".streaming").show();
} else {
jQuery(".streaming").hide();
}
function showForDay(d){
// put all your conditions here
if (d.getDay() == 0 && d.getHours() >= 9 && d.getHours() <= 12) return true
if (d.getDay() == 0 && d.getHours() >= 12 && d.getHours() <= 14) return true
...
return false // will be hidden
}
Related
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';
}
}
};
I'm trying to figure out how to make "open" display between 11:00 am to 8:30 pm (20:30) using only pure javascript for a local business. I can get it to work for 11:00 am to 8 pm (20:00) but I can't figure out how to get it to work for 20:30.
const paragraph = document.querySelector("#openClose");
let d = new Date();
let day = d.getDay();
let hours = d.getHours();
let minutes = d.getMinutes();
if (day === 5 && hours >= 11 && hours < 20) {
openClose.textContent = "Open."
} else {
openClose.textContent = "Closed."
}
//I tried, among other things:
if(day === 5 && hours >= 11 && hours < 20 && minutes < 30) {…
I read this stackoverflow article, but missed something, it didn't help me.
Think about what you're asking: you want it to work from 11 to 20 regardless of minutes, and then also work for 20 up to 30 minutes past. So that's two partitions of the hours, and one of the minutes, meaning you'll need two different terms in your condition.
if ((hours >= 11 && hours < 20) || (hours === 20 && minutes < 30)) { /* ... */ }
Change your if statement to:
if (day === 5 && ((hours >= 11 && hours < 20) || (hours === 20 && minutes < 30)))
Try with this
if(day === 5 && hours >= 11 && // this always matters
(
hours < 20 || // if it's less than 20 minutes don't matter
(hours === 20 && minutes < 30) // if it's 20 then minutes matter
)
)
As per the day
The getDay() method returns the day of the week (from 0 to 6) for the specified date.
Note: Sunday is 0, Monday is 1, and so on.
I'm trying to setup a popup message at a specific time on all weekdays and saturdays. Should be fairly simple, and I'm aware that this could be done using arrays and so on, but please bear with me, as i'm kinda new to this.
What I have so far, looks like this:
<script type="text/javascript">
var day = day.getday();
var hr = day.getHours();
if ((hr < 10) && (hr > 18) && (day == 1) || (hr < 10) && (hr > 18) && (day == 2) || (hr < 10) && (hr > 18) && (day == 3) || (hr < 10) && (hr > 18) && (day == 4) || (hr < 10) && (hr > 18) && (day == 5))
{
document.write("test");
}
Any help would be much appreciated.
Here is a messy example that shows an approach that you can take... Not all code-paths are completed (like hooking up the event for tomorrow if the connfigured hour/min is already passed) but...it does show a message at a configured hour/min of the day if that day is any day other than Sunday.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var showPopup = function()
{
document.write("test");
alert("Show Message!");
};
var hookupAlert = function(targetHour, targetMin)
{
var nextAlert = null;
var now = new Date(); // Now.
var day = now.getDay(); // Returns 0-6 where 0=Sunday, 6=Saturday.
var hr = now.getHours(); // Returns 0-23.
var min = now.getMinutes(); // Returns 0-59.
// If a weekday or saturday.
if(day != 0)
{
// Is it before the target hour/min?
if(hr <= targetHour && min < targetMin)
{
nextAlert = new Date(now.getFullYear(), now.getMonth(), now.getDate(), targetHour, targetMin, 0);
}
else
{
// We've passed the target hour/min for the day...
// TODO: Possibly determine tomorrow (or if tomorrow is Sunday, the day after).
console.log("Passed the targetHour & targetMin for the day.");
}
}
if(nextAlert)
{
var diffInMs = Math.abs(nextAlert - now);
window.setTimeout(showPopup, diffInMs);
}
};
// Make the call to hook up the alert at 11:15.
hookupAlert(11, 15); // Hour between 0-23, Min between 0-59.
</script>
</body>
I hope this helps.
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;
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
}