Retrieve the current day's value from an array

I have a list of days with corresponding opening and closing hours, now I need to find the operating hours for today. For instance, if it's Friday, then the current hours should be "11:30 AM – 9:30 PM". How can I achieve this using JavaScript?

["Monday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM", "Tuesday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM", 
 "Wednesday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM", "Thursday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM", 
 "Friday: 11:30 AM – 9:30 PM", "Saturday: 11:30 AM – 9:30 PM", 
"Sunday: 11:30 AM – 9:00 PM"]

let currentTime = new Date().toString().split(' ')[4];
let a = currentTime.split(':');
if(a[2]>1){
  a[1]=parseInt(a[1])+1
}
let hours = a[0]
let minutes = a[1]

Furthermore, how do I determine if a specific time (e.g., 15:02:01pm) falls within the operating hours like between 11:30 AM – 2:30 PM or 15:02:01pm between 11:30 AM – 2:30 PM, 5:30 – 10:30 PM?

Answer №1

Retrieve the current day of the week ranging from 0 (Sunday) to 6 (Saturday):

const today = new Date().getDay();

Adjust it to align with the array, where 0 represents Monday:

const today = (new Date().getDay() + 6) % 7;

Eliminate the day name in the corresponding entry:

const values = ["Monday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM", …];
const value = values[today].split(': ')[1];

Creating a function for parsing input time might be helpful at this stage, returning the minutes passed since midnight:

const parseInputTime = time => {
    const [hours, minutes] = time.split(':').map(Number);

    return 60 * hours + minutes;
};

The process of parsing time within a range is similar:

const parseRangeTime = time => {
    const parts = time.split(/[: ]/);
    const hours = parseInt(parts[0], 10) + (parts[2] === 'PM' ? 12 : 0);
    const minutes = parseInt(parts[1], 10);

    return 60 * hours + minutes;
};

Now you can utilize these functions and compare the outcomes:

const [start, end] = value.split(' – ');
const isInRange =
    parseInputTime(currentTime) >= parseRangeTime(start) &&
    parseInputTime(currentTime) < parseRangeTime(end);

complete demonstration

Answer №2

Yes, this method is effective.

const appointments = ["Monday: 9:00 AM – 2:00 PM", "Tuesday: 10:00 AM – 3:00 PM", 
 "Wednesday: 8:30 AM – 1:30 PM", "Thursday: 11:30 AM – 4:30 PM", 
 "Friday: 7:00 AM – 12:00 PM", "Saturday: 9:00 AM – 5:00 PM", 
"Sunday: Closed"]

let currentDay = new Date().toLocaleString('en-us', { weekday: 'long' })

let todaySchedule = '';

for (let j=0; j < appointments.length; j++) {
  if (appointments[j].indexOf(currentDay) !== -1 ) {
    todaySchedule = appointments[j].substr(currentDay.length + 2)
  }
}

console.log(todaySchedule);

Answer №3

Give this a try

let schedule = ["Monday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM", "Tuesday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM",
 "Wednesday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM", "Thursday: 11:30 AM – 2:30 PM, 5:30 – 10:30 PM",
 "Friday: 11:30 AM – 9:30 PM", "Saturday: 11:30 AM – 9:30 PM",
"Sunday: 11:30 AM – 9:00 PM"];

for(let j=0; j<schedule.length; j++){console.log(schedule[j].substring(0,schedule[j].indexOf(':')));}

Answer №4

Feel free to give this a try. I've made some changes to how the data is being stored.

var array  = [
            {name: "Monday", value :"11:30 AM – 2:30 PM, 5:30 – 10:30 PM"}, 
            {name: "Tuesday", value :"11:30 AM – 2:30 PM, 5:30 – 10:30 PM"}, 
            {name: "Wednesday", value :"11:30 AM – 2:30 PM, 5:30 – 10:30 PM"}, 
            {name: "Thursday",  value :"11:30 AM – 2:30 PM, 5:30 – 10:30 PM"}, 
            {name: "Friday  ", value : "11:30 AM – 9:30 PM"}, 
            {name: "Saturday", value : "11:30 AM – 9:30 PM"}, 
            {name: "Sunday  ", value : "11:30 AM – 9:00 PM"}
           ];
            
           function myFunction() {
            var obj = array.filter(function ( obj ) {
            return obj.name === 'Wednesday';
            })[0];
        
            window.alert(obj.value);  
           } 
<!DOCTYPE html>
<html>
  <body>
        <button onclick="myFunction()">Click me</button>
  </body>
</html>

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

When using Node.js with Nginx, requests are timing out at the Nginx level before the processing is completed in Node.js

I have a setup where I use Nginx and Node.js servers. The process involves uploading a file from a browser to Nginx, which then forwards it to Node.js for processing. However, I've encountered an issue when dealing with large files - the upload crashe ...

How can I access a PHP variable from an external .php file within a JavaScript script?

I have recently implemented a JavaScript code called "upload.js" for uploading files to my server: function beginUpload(){ document.getElementById('upload_form').style.visibility = 'hidden'; return true; } function endUpload(s ...

Unable to navigate using ui-sref or $state.go in initial directive execution

There seems to be an issue with my ng-repeat on a directive where I'm passing in 3 pieces of information. The directive includes a button that is supposed to pass that information on to another view using params like this: ui-sref='profiles.sho ...

Is there a way to rigorously validate my HTML, CSS, and JavaScript files against specific standards?

Can modern browsers suppress errors in HTML, CSS, and JS sources? Is there a method to uncover all mistakes, no matter how small they may be? ...

Loading an empty CSS file in Node.js

Just starting out with node.js, and I could really use some help with a small css and image issue that I'm facing. I've streamlined my html and .js for clarity. Despite trying everything, the css and image just won't load. My form and server ...

Bringing the value from the codebehind to the jquery function on the client side

Here is the code snippet from my asp.net web application's code behind where I have integrated another web service: [WebMethod] public static string GetData(string name) { WEBSERVICE.Service1 Client = new Service1(); string Nam ...

ShadowBox not displaying Vimeo videos

I can't figure out why my Vimeo videos are not appearing in a Shadowbox. I have followed the steps I know to be the simplest, which involve copying the example directly from the github page and then updating the shadowbox paths to match the locations ...

Modifying the app.css file in the source tab of dev tools does not cause any changes in the DOM when working with a

Just starting out with react js here. While exploring developer tools in Chrome, I attempted to tweak some CSS in the elements panel and noticed the changes reflecting above in the DOM. However, when I navigate to the sources tab, I'm unable to modify ...

String constant without an ending

My Description has a single quote character('). How can I make sure it doesn't break the code? <a href='javascript:select("<%= pageBean.replace(list.getColumn(0), "'", "'") %>", "<%= pageBean.replace(list.getColumn(1), ...

Send a JavaScript object to an MVC controller using an HTTP POST request

I'm encountering an issue while attempting to send a JavaScript object containing a string and a jstring to an MVC controller. Despite my code looking correct, I am receiving a null value in the controller. Any assistance would be greatly appreciated. ...

Enhancing Forms with Redux and Styled Components

I'm currently working on developing a reusable component that involves using a redux-form <Field /> and styling it with styled-components within the component. The issue I'm facing is that none of the styles are being applied. Here is my ...

The feature of determining if an edge exists, within the dagre-d3/graphlib,

Has anyone utilized the graph.hasEdge function in dagre-d3/graphlib to check for the existence of an edge between two nodes? This API takes two arguments representing the two nodes and verifies if there is an edge connecting them. I am facing an issue whe ...

Accessing the app module in separate files is not possible for Angular and Coffeescript

As I work on managing and refactoring my Angular code in a Rails project with CoffeeScript, I am facing issues accessing Angular objects between multiple files. Here is the current file structure: javascripts |-Angular |-controllers | |-search_strl.js ...

Is it a Javascript comparison glitch, or have I overlooked something important?

Recently, I've been working on a JavaScript code that is designed to retrieve data from a server regarding the temperature readings from 2 sensors. The data is stored in a text file where each line includes a date along with 2 values corresponding to ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

What's the reason behind the console showing an uncaught promise error message?

When attempting to delete some lists from my backend using a fetch request, I encountered an issue. The console is displaying an error message that reads "Uncaught (in promise)." What could be causing this problem? Here is the frontend code snippet for th ...

The PHP page is not receiving the variable passed through AJAX

Within the following code snippet, there seems to be an issue with accessing the dataString variable in the comment.php page. To retrieve the variable name, I utilized $_POST['name']. $(document).ready(function(){ $("#submit").click( function() ...

Searching for a specific result in MongoDB using Node.js by its ID

Having recently started working with Node.js, I have encountered an issue that I can't seem to solve no matter what. Here is the simple code snippet that I am struggling with: var express = require("express"); var mongoose = require("mongoose"); var ...

Upload multiple files at once, edit span text, and retitle to files chosen

I need help updating the span text for each file uploader on my page. I want the default "Choose a file..." text to change to the selected filename. Can someone assist me with this? Here is a Js fiddle that I've been working on. This is my HTML mark ...

communicating data within a JavaScript file across server and client

One of my files, parameters.js, contains the following JavaScript code: const myJSON = { parameter1: 2, parameter2: 2. } module.exports = {myJSON} In another file called server.js, I can access this data by usin ...