Javascript time between 08:30 - 20:00 - javascript

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
}

Related

Check if time is within time bounds with minutes

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';
}
}
};

Javascript script for identifying multiple days of the week

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
}

jscript/html popup at specifc time

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.

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 to Output Text Based on User's Current Time

I don't know JavaScript, but I am familiar with following directions. I know a little PHP.
I'm looking for a piece of JS that will output a particular string of text for my header, based on the user's current time.
For example:
12:00AM - 12:00PM - Good Morning!
12:00PM - 6:00PM - Good Afternoon!
6:00PM - 12:00AM - Good Evening!
Try following piece of Javascript code:
var today = new Date()
var curHr = today.getHours()
if (curHr < 12) {
console.log('good morning')
} else if (curHr < 18) {
console.log('good afternoon')
} else {
console.log('good evening')
}
var data = [
[0, 4, "Good night"],
[5, 11, "Good morning"], //Store messages in an array
[12, 17, "Good afternoon"],
[18, 24, "Good night"]
],
hr = new Date().getHours();
for(var i = 0; i < data.length; i++){
if(hr >= data[i][0] && hr <= data[i][1]){
console.log(data[i][2]);
}
}
Demo: http://jsfiddle.net/DerekL/we8Ty/
This is just a small variation of the solution from Derek 朕會功夫 above.
I felt the array is cleaner than a bunch of if statements.
If you work the hours backwards, you don't need a start AND end hour.
Also, once you make a match, I added a break; to kick out early.
var data = [
[22, 'Working late'],
[18, 'Good evening'],
[12, 'Good afternoon'],
[5, 'Good morning'],
[0, 'Whoa, early bird']
],
hr = new Date().getHours();
for (var i = 0; i < data.length; i++) {
if (hr >= data[i][0]) {
console.log(data[i][1])
break;
}
}
I know this is an old thread, i'm just sharing this 2 lines of code for anyone who needs simple solution :)
var hour = new Date().getHours();
console.log("Good " + (hour<12 && "Morning" || hour<18 && "Afternoon" || "Evening"))
const date = new Date();
const currentTime = date.getHours();
let greeting;
if (currentTime >= 0 && currentTime <= 12) {
greeting = "Good Morning";
} else if (currentTime > 12 && currentTime <= 18) {
greeting = "Good Afternoon";
} else {
greeting = "Good Evening";
}
ReactDOM.render(
<h1>{greeting}</h1>,
document.getElementById("root")
);
How about:
var time = new Date().getHours();
,greeting = 'Good '+ (time < 12 ? 'Morning' :
time < 18 ? 'Afternoon' : 'Evening');
//=> new Date('2012/11/06 13:10') => 'Good Afternoon'
//=> new Date('2012/11/06 10:33') => 'Good Morning'
//=> new Date('2012/11/06 19:23') => 'Good Evening'
Or augment Date
Date.prototype.greeting = function(){
var time = this.getHours();
return 'Good '+ (time<12 ? 'Morning' : time<18 ? 'Afternoon' : 'Evening');
};
new Date('2012/11/06 19:23').greeting() //=> 'Good Evening'
see jsfiddle
Try this js code, This should work..
var dt = new Date().getHours();
if (dt >= 0 && dt <= 11){
console.log('GM')
}else if (dt >= 12 && dt <= 17){
console.log('Good Afternoon!')
}else {
console.log('GE')
}
This should help you:
const currentTime = new Date().getHours();
let greetingText = "";
if (currentTime < 12) {
greetingText = "Good Morning";
} else if (currentTime < 18) {
greetingText = "Good Afternoon";
} else {
greetingText = "Good Evening";
}
I haven't tested but it should work:
function getText()
{
var hour = new Date().getHours();
var minute = new Date().getMinutes();
if ( hour >= 0 && hour < 12 )
return 'Good Morning!';
else if ( hour == 12 && minute == 0 )
return 'Good Morning!';
else if ( hour == 12 && minute > 0 )
return 'Good Afternoon!';
else if ( hour == 6 && minute == 0 )
return 'Good Afternoon!';
else if ( hour == 6 && minute > 0 )
return 'Good Evening!';
else if ( hour > 12 && hour < 6 )
return 'Good Afternoon!';
else if ( hour > 6 && hour < 12 )
return 'Good Evening';
}
<script type="text/javascript">
var myDate = new Date();
var name = window.prompt("Please enter your name: ");
if (myDate.getHours() < 12) {
document.write("Good Morning " +name);
}
else if(myDate.getHours() >=12 && myDate.getHours() <=17){
document.write("Good Afternoon " +name);
}
else if (myDate.getHours() > 17 && myDate.getHours() <=24) {
document.write("Good Evening " +name);
}
else
{
document.write("Good Night");
}
</script>
With moment.js & ES6:
import moment from 'moment';
console.log(`${getGreetingTime(moment())} ${userFirstName}`);
getGreetingTime = (currentTime) => {
if (!currentTime || !currentTime.isValid()) { return 'Hello'; }
const splitAfternoon = 12; // 24hr time to split the afternoon
const splitEvening = 17; // 24hr time to split the evening
const currentHour = parseFloat(currentTime.format('HH'));
if (currentHour >= splitAfternoon && currentHour <= splitEvening) {
return 'Good afternoon';
} else if (currentHour >= splitEvening) {
return 'Good evening';
}
return 'Good morning';
}
Adapted from James1x0's gist.
var today = new Date();
var curHr = today.getHours();
if (curHr < 12) {
console.log('good morning')
} else if (curHr >= 12 && curHr < 16) {
console.log('good afternoon')
} else {
console.log('good evening')
}
var day=new Date();
var hr=day.getHours();
ReactDOM.render(
<div>
<h1>
{"Good"+ (hr< 12 ? "Morning": hr < 18 ? "Afternoon" :"Evening")}
</h1></div>,document.getElementById("root"));
This is what I used
import React from "react";
import ReactDOM from "react-dom"
const today = new Date().getHours();
let greeting;
if (today < 12) {
greeting = "Good Morning"
} else if (today < 18) {
greeting = "Good Afternoon"
} else {
greeting = "Good Night"
}
Another way with ES6 and Moment.js
import moment from 'moment';
const getGreetingTime = () => {
const splitMorning = 6;
const splitAfternoon = 12;
const splitEvening = 17;
const splitNight = 20;
const currentHour = parseFloat(moment().format('HH'));
if (currentHour >= splitMorning && currentHour <= splitAfternoon) {
return 'Good morning';
} else if (currentHour >= splitAfternoon && currentHour <= splitEvening) {
return 'Good afternoon';
} else if (currentHour >= splitEvening && currentHour <= splitNight) {
return 'Good evening';
}
return 'Good night';
};
const greeting = getGreetingTime();
Try this
if (hour >= 0 && hour < 3){
return 'Good Late Night!';
}
else if (hour >= 3 && hour < 12){
return 'Good Morning!';
}
else if (hour == 12 && minute == 0){
return 'Good Morning!';
}
else if (hour == 12 && minute > 0){
return 'Good Afternoon!';
}
else if (hour == 6 && minute == 0){
return 'Good Afternoon!';
}
else if (hour == 6 && minute > 0){
return 'Good Evening!';
}
else if (hour > 12 && hour <= 15){
return 'Good Noon!';
}
else if (hour > 15 && hour <= 6){
return 'Good Afternoon!';
}
else if (hour > 6 && hour < 12){
return 'Good Evening';
}
I have created a pure TypeScript function:
type SayHelloProps = {
morning: string;
afternoon: string;
evening: string;
};
const sayHello = ({
morning,
afternoon,
evening
}: SayHelloProps): string => {
const currentTime = new Date();
const currentHour = currentTime.getHours();
switch (true) {
case currentHour < 12:
return morning;
case currentHour > 12 && currentHour < 17:
return afternoon;
default:
return evening;
}
};
Readable, easy to use.

Categories

Resources