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.
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 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
}
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
}
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;
Hey, how do you refresh a div on a certain hour?
So the timed based greeting ticks over automatically.
the code I have at the moment is this:
<div id = "greet" ><script>
var Digital=new Date()
var hours=Digital.getHours()
if (hours < 12)
document.write('Good morning.')
else if (hours >= 12 && hours < 18)
// (code in here?) refresh the div at 12:00 pm
document.write('Good afternoon.')
else if (hours >= 18 && hours <= 24)
// (code in here?) refresh div at 6:00 pm
document.write('Good evening.')
</script></div>
any tips would be great.
cheers.
are you need like this
var datas="";
var Digital=new Date()
var hours=Digital.getHours()
if (hours < 12){
datas = 12 ? "is a below 12am" : "";
document.write('Good morning.')
}
else if (hours >= 12 && hours < 18) {
datas = 12 ? "is a 12am" : "";
document.write('Good afternoon.')}
else if (hours >= 18 && hours <= 24){
datas = 18 ? "is a 6pm" : "";
document.write('Good evening.')
}
document.getElementById('greet').innerHTML=datas;
<div id = "greet" ></div>