What is the best way to ensure that this JavaScript code functions properly when dealing with business operating hours

Using this javascript code allows me to check if a business is open based on its operating hours. It's effective for times like 17:00-23:00, but how can I modify it to work for hours past midnight, such as 0:30 or 1:00 in the morning?

var d = new Date();
var n = d.getDay();
var now = d.getHours() + "." + d.getMinutes();
var weekdays = [
    ["Sunday", 9.30, 12.00, 15.30,22.00],
    ["Monday", 8.30, 12.00, 15.30,19.00],
    ["Tuesday", 8.30, 12.00, 15.30,19.00],
    ["Wednesday", 8.30, 12.00, 15.30,19.00],
    ["Thursday", 8.30, 12.00, 15.30,19.00],
    ["Friday", 8.30, 11.30],
    ["Saturday"] // we are closed, sorry!
];
var day = weekdays[n];


if (now > day[1] && now < day[2] || now > day[3] && now < day[4]) {
    console.log("We're open right now!");
}
 else {
    console.log("Sorry, we're closed!");
}

I understand that this script doesn't account for timezones, but since it's designed for local businesses, which operate in the same timezone as their clients, this isn't an issue.

Thanks in advance. PS: The original script was adapted from another post on stackoverflow Javascript Store Opening Hours

UPDATED VERSION: I made changes to the script because I now retrieve opening hours data from Firebase in JSON format, eliminating the need for the days array.

<script>

    var d = new Date();
    var n = d.getDay();
    var now = d.getHours() + "." + d.getMinutes();

    // Data retrieved from firebase 
    var day = {
    "from": 8.30,
    "to": 10,
    "from2": 14.30,
    "to2": 23    
    };

console.log('Now: ' + now);

    if (now > day.from && now < day.to || now > day.from2 && now < day.to2) {
        console.log("We're open right now!");
    } else {
        console.log("Sorry, we're closed!");
    }

</script>

However, this setup fails when dealing with time ranges like 17:00-01:00.

Answer №1

Through experimentation, I discovered a solution on my own. I crafted a small function that allows you to input open and closed times and receive a response regarding whether the business is currently open or closed. This function is versatile and can handle all times, even spanning past midnight.

However, it's essential to note that this script may not be suitable for businesses in different timezones as it doesn't account for location-based times. It functions effectively when used for local businesses operating within the same timezone as their clients.

// Here's an example using JSON data for the current day.
var day = {
   "from": 17.30,
   "to": 1.30
};

var check_now = check_business_status(day.from, day.to);
console.log('The business is ' + check_now);

function check_business_status(from, to) {

    var d = new Date();
    var n = d.getDay();
    var now = d.getHours() + "." + d.getMinutes();

    console.log('Now: ' + now);
    console.log(from + ' // ' + to);

    // Checking if the closing time falls after midnight.
    if (from > to){
        console.info('Closing time is after midnight! Special Check...');

        var status = '';
        if (now < to && from > now) {
            status = "open";
        } else if (now > to && from > now) {
            status = "closed";
        } else if (now > to && from < now && now > from) {
           status = "open";
        }

    } else {
        console.info('Closing time is before midnight! Normal Check...');
        if (now > from && now < to) {
            status = "open";
        } else {
            status = "closed";
        }
    }
     return status;
}

To further test this functionality with various timings, visit jsfiddle https://jsfiddle.net/oliver2000/4pdogett/1/

Answer №2

Utilizing either Local time or a date library such as or https://momentjs.com/ can assist in managing date-time data.

By parsing (new Date).toLocaleString(), you can manipulate your data according to this specific date and time.

var date = new Date();
var formatted = date.toLocaleString('de-DE');

To determine the timezone, you can utilize navigator.language.

Answer №3

Check out this code snippet for a possible solution:


var currentDate = new Date();
var currentDay = currentDate.getDay();
var currentTime = currentDate.getHours() + "." + currentDate.getMinutes();
var schedule = [
    ["Sunday", 9.30, 12.00, 15.30, 19.00],
    ["Monday", 8.00, 12.00, 15.30, 19.00],
    ["Tuesday", 8.30, 12.00, 15.30, 19.00],
    ["Wednesday", 8.30, 12.00, 15.30, 19.00],
    ["Thursday", 8.30, 12.00, 15.30, 19.00],
    ["Friday", 8.30, 11.30],
    ["Saturday"] // Closed
];
var currentSchedule = schedule[currentDay];

if ((currentTime < currentSchedule[1] && currentTime > currentSchedule[2]) || (currentTime < currentSchedule[3] && currentTime > currentSchedule[4])) {
      console.log("Sorry, we are closed right now!");
}
else {
   if(currentDay != 0){
     currentSchedule = schedule[currentDay - 1];
   }
   else{
     currentSchedule = schedule[6]; // Saturday's schedule since it's Sunday
   }

   if (currentTime > currentSchedule[4]) {
     console.log("Sorry, we are closed right now!");
  }
   else {
     console.log("We're open at the moment!");
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to execute findOneAndUpdate as a function

I've been researching all morning and testing different solutions, but I'm still unable to resolve this issue. Every time I run the code below, I receive the error "TypeError: req.user.findOneAndUpdate is not a function": req.user.findOneAndUpd ...

Need to `come back` multiple times

I am facing an issue where I want to return multiple lines, but only the first line is being returned. I attempted to create a function specifically for returning the line, but encountered errors because I couldn't figure out where to place it. Does ...

Disabling caching in bootstrap tabs for loading ajax content

My goal is to make bootstrap tabs load content through ajax queries. While this process is straightforward with Jquery tabs, which default to loading content via ajax query, it seems to be a different case for bootstrap. As such, I have come across the fo ...

How can we refine the user information based on the selection of a radio button?

How do I apply a filter to user details when selecting a radio button? Visit Plunker *I need to display only the questions of authenticated users on the list page, so I created a plunker example. If the user is authenticated or an admin, I want to filter ...

The issue of actions failing to flow from sagas to reducers in React.js

Upon user login, the success response is received but the action is not passed to the reducer. Strangely, during user registration, everything works smoothly. //saga.js import { put, takeEvery, all, call } from 'redux-saga/effects'; import {getRe ...

Achieving nested routes without the need for nested templates

My Ember routes are structured like this: App.Router.map(function() { this.resource("subreddit", { path: "/r/:subreddit_id" }, function() { this.resource('link', { path: '/:link_id'} ); }); }); However, ...

What could be the reason for the incorrect parsing of this JSON data?

Issue arising due to unparseable JSON in JavaScript and jQuery API. Here is the code snippet: JSON parsing issue in JavaScript: // Code sample: alert(data); // output is an object alert(data.horas[0].hora; // returns undefined The JSON structure: {"hor ...

Enter information to accompany your images in the description box

After browsing through numerous websites tonight, I stumbled upon this code. My goal is to create a photo upload page on Google Drive and set up a dropbox for it. I'm facing an issue where the information inputted into my placeholder box (city and ye ...

The issue of Angular JQuery Datepicker failing to set the MinDate upon initialization

In my AngularJS project, I am using JQuery UI's Datepicker for the Date From and Date To fields. I have successfully bound the value to the model using a directive, and I have also implemented logic in the OnSelect function to ensure that the Date To ...

Alert message in jQuery validation for the chosen option value

I am attempting to validate a combo box with the code provided below. Currently, I receive multiple alert messages even if one condition is true. My goal is to only display one alert message when a condition is met and highlight the other values in red. Th ...

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...

What are the appropriate levels of access that an operating system should provide for web-based scripting?

Contemplating the level of access web-based applications have to an operating system has been on my mind. I'm pondering: What is the most effective method for determining this currently? Are we seeing a trend towards increased or decreased access? ...

There seems to be a problem with the external JavaScript file not functioning

After dragging and dropping the .js file into my ASP.NET project, I am facing an issue where it remains unresponsive, even though the code works fine when used inline. This problem is occurring while using VS 2017. Here is a snippet of my code: <scrip ...

Uncaught TypeError: Cannot read property 'e' of undefined in vue.js

Feeling a bit frustrated now :( This is my first time trying to use vue.js, which comes after jQuery as the second JS framework I'm diving into on this planet. Here's the HTML code I have: var main = new Vue({ el: ".main-content", data: { ...

Steps to create an iframe that opens in a new window

I'm facing an issue with the iframe sourced from flickr. My website includes an embedded flickr iframe to showcase a gallery without the hassle of creating a slider, resizing images, and extracting thumbnails. Given that this site belongs to a frien ...

Is there a workaround for the issue with AngularJs ng-disabled not functioning in Internet Explorer 9?

Having an issue with the ng-disabled directive in AngularJS. It works well in Chrome, but not in IE 9. Any suggestions on how to make it work in IE 9 would be greatly appreciated. main.html <select kendo-drop-down-list k-data-text-field="'text&a ...

Getting the project path in the Sonarqube JavaScript Extension is a straightforward process

I am currently developing a custom rules plugin for the SonarQube Javascript Plugin. I have encountered an issue where I need to disable certain checks in specific directories, such as the bin path. My main question is: how can I obtain the file path rela ...

Modifying the data of an HTML form using Javascript, encrypting the information, and transferring it to PHP

I am new to PHP and have a simple code management question. I would like to create an input box in HTML where someone can enter their name, and with the use of Javascript, generate a link with an encoded version of the name preceded by a website string. Wh ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...