What is the best technique for evaluating different businesses' operating hours?

I am trying to compare the opening hours stored on my server with the current time.

Here are the details:

Start: 09.00 End: 00.30

The goal is to determine if the store is open or closed based on the current time. If the current time falls outside of the given start and end times, the store is considered closed.

However, the code I have been using so far is not functioning correctly. It is giving me the following error message:

TypeError: Cannot read property '3' of undefined

firebase.database().ref("v3/standalonelist/bars").on('value', function(snapshot) {

    $timeout(function() {
      $scope.content = snapshot.val();
      snapshot.forEach(function(childSnapshot) {

        $scope.data1 = [childSnapshot.val()];
        $scope.locations1 = $scope.data1

        $scope.locations1.forEach(function(item) {

        $scope.getMinutes = function(str) {
                var time = str.split('.');
                return time[0] * 60 + time[1] * 1;
              }
              $scope.getMinutesNow = function() {
                var timeNow = new Date();
                return timeNow.getHours() * 60 + timeNow.getMinutes();
              }
              var a = new Date();
              var day = a.getDay(); // 3
              var now = $scope.getMinutesNow();
              console.log(item.opens[day]); // returns 09.00
              var start = $scope.getMinutes(item.opens[day]); // 09.00
              var end = $scope.getMinutes(item.closes[day]); // 01.20
              if (start > end) {
                end += $scope.getMinutes('24.00');
              }

              if ((now > start) && (now < end)) {
                $scope.$apply(function() {
                  $scope.open = true; // Store is open
                })

              } else {
                $scope.open = false; // Store is closed
              }
         })
       })

Answer №1

Perhaps you are overcomplicating things a bit...

let today = new Date(),
    open = "Open",
    closed = "Closed",
    display = document.getElementById('display'),
    start = new Date(), end = new Date();

// Set the opening hour:minutes
start.setHours(10);
start.setMinutes(5);
// Set the closing hour:minutes
end.setHours(18);
end.setMinutes(30);

// Check the time based on milliseconds
if (
    today.getTime() >= start.getTime() && 
    today.getTime() < end.getTime()
) {
    display.innerHTML = open;
} else {
    display.innerHTML = closed;
}

You can view a working example here: http://jsfiddle.net/L770r2qk/

If your business operates during late night to early morning hours, consider using start.setDate(12) and end.setDate(13). For month changes, utilize start.setMonth(10) and end.setMonth(11).

Add these extra features as needed for your specific requirements.

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

What is the best way to retrieve the value of a textbox in AngularJS?

Trying my hand at creating a basic web page using angular. I've got 2 textboxes and 2 buttons - one to set a predefined value in a textbox, and the other to add some text. Here's the code snippet: <!DOCTYPE html> <html lang="en" ng-app ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Traditional Javascript is unable to add elements to the DOM

I am currently facing an issue with my website that is built in Expression Engine. The back-end of the website contains a code snippet responsible for handling a JavaScript request and generating a page based on that request. One of the challenges I am en ...

How can I fetch data from a PHP file using an Ajax request?

Recently, I delved into the realm of Ajax requests and devised this script: function ajax_post(){ // Initiating XMLHttpRequest object var xmlhttp = new XMLHttpRequest(); // Setting up necessary variables for sending to PHP file var url = " ...

Unable to Get Basic jQuery .load Example to Function

Seeking assistance with a jQuery issue regarding loading HTML snippets into a page. When the snippet contains just HTML, it loads fine. However, when it includes a script, there seems to be an issue. Simplified code provided below for better understandin ...

Struggling to make addClass and removeClass function correctly for the development of the unique "15 puzzle" game

I am currently in the process of creating a version of "the 15 game" using jQuery in HTML. You can find more information about the game on this page. The objective of the game is to rearrange a table of "boxes" in ascending order from 1 to 15. Below is th ...

404 Error: The requested resource is not available on the web API

I have been attempting to utilize Web Api to send/receive data from the server. In my WebApiConfig.cs file: config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{controller}/{act ...

What could be causing the JavaScript/jquery code in my Functions.php file to only function properly on the initial post that loads on my WordPress website?

Currently, I am in the process of developing a WordPress website where the content is refreshed weekly. This means that all posts, media, and files are removed from the WP environment every week and replaced with new content. One of the key components of ...

The utilization of useEffect causes the page to go blank

Essentially, the issue is that once I include useEffect(() => { const fetchData = async () => { const result = await fetch('http://localhost.com/ping'); console.log(result) }; fetchData(); }, []); in my compone ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...

Issue with scrolling in angular-ui-bootstrap modal on Apple devices with the mobile web app capability enabled

I've encountered a problem with a basic to-do list web application that I'm currently developing. In order to enable the iPhone standalone launch feature, I have included the following code: <meta name="apple-mobile-web-app-capable" content=" ...

What is the best way to center align and add an icon to the header in Ionic?

How can I center align an "ion-ios-arrow-up" icon in the header of my Ionic app, similar to the concept shown below? This is my HTML template: <ion-view cache-view="false" view-title="Historical HPP"> <ion-nav-bar class="nav-title-slide-ios7 ...

Trouble with Title Updating in Next.js and Tailwind CSS Project

I am currently facing an issue with the title of my website not updating, even though I am using next/Head and have included the title tag. "use client"; import Head from 'next/head'; import { BsFillMoonStarsFill } from 'react-ico ...

What could be causing my data to shift after refreshing in Firefox with the F5 key?

My webpage has four tables, each containing rows with two text boxes filled with numeric values from the server. However, something peculiar occurs. When I add data to a row, let's say row 1, and then refresh the page, two values are mysteriously mov ...

Changing the border of an iframe element using jQuery or Javascript from within the iframe itself

Is it possible to set the border of an iframe to zero from within the iframe itself using JavaScript or jQuery? Any guidance on how this can be achieved would be greatly appreciated. Thank you! ...

Passing objects to an AngularJS form using UIB TypeAhead without two-way binding

In my current situation, I am encountering an issue with a typeahead feature on a repeating form element that consists of 5 input fields. While everything functions correctly when selecting results and populating the input fields, the model does not get up ...

CKEditor with Readonly Option and Active Toolbar Controls

In my current Rails project, I have successfully set up a CKEditor instance in readOnly mode. Everything is functioning as expected. Now, I am attempting to add a custom plugin button to the toolbar while keeping the textarea in readOnly mode. After some ...

The nightmare of Parent-Child Inheritance in JQuery/CSS is a constant struggle

Having difficulty implementing specific JQuery effects into a Bootstrap framework due to its extensive CSS causing issues. Created a test file named testjquery.html connected to a stylesheet defining a hidden element and activating the fade in of this ele ...

Shared codes are compatible with both C and Javascript programming languages

Within the scope of this project, data will be retrieved from the server in either JSON or XML format. There are two separate client applications that will handle the data processing, with one being web-based and written in JavaScript, while the other is ...

Sort the array based on the enum name rather than its value

Below is an example of an enumeration: export enum Foo { AA = 0, ZZ = 1, AB = 2, ER = 5 } In my case, I want to sort my Bars based on the name of the enum (AA, AB, ER, ZZ), rather than the numerical value (0, 1, 2, 5) that they represent. ...