Retrieve the array element that contains a date range matching the current time using JavaScript

I've been searching on Stack for an answer to my question, but I haven't found a solution yet. My issue is that I need to display only the object in my array where the current time falls within the specified date range defined by timeStart and timeEnd. For example, if the current time is 2020-10-22T16:35:45+01:00, the function should display Steve's appointment. How can I find the object with the current time within the given date ranges?

const currentTime = Date.now(); // 2020-10-22T16:35:45+01:00

Here is the array I'm dealing with:

[
    {
        name: "Thomas",
        timeStart: "2020-10-22T16:00:00+0100",
        timeEnd: "2020-10-22T16:15:00+01:00"
    },
    {
        name: "Marc",
        timeStart: "2020-10-22T16:15:00+0100",
        timeEnd: "2020-10-22T16:30:00+01:00"
    },
    {
        name: "Steve",
        timeStart: "2020-10-22T16:30:00+0100",
        timeEnd: "2020-10-22T16:45:00+01:00"
    }
]

Answer №1

Examine the start, end, and current dates within a loop utilizing the find method.
If the comparison yields true, the current object will be returned; otherwise, undefined.

const now = new Date("2020-10-22T16:17:00+01:00"); // 16:17. Should be Marc.

const dates = [
    {
        name: "Thomas",
        timeStart: "2020-10-22T16:00:00+0100",
        timeEnd: "2020-10-22T16:15:00+01:00"
    },
    {
        name: "Marc",
        timeStart: "2020-10-22T16:15:00+0100",
        timeEnd: "2020-10-22T16:30:00+01:00"
    },
    {
        name: "Steve",
        timeStart: "2020-10-22T16:30:00+0100",
        timeEnd: "2020-10-22T16:45:00+01:00"
    }
];

const result = dates.find(({ timeStart, timeEnd }) => {
  const start = new Date(timeStart);
  const end = new Date(timeEnd);
  return start <= now && end > now;
});

console.log(result);

Answer №2

Do you find this effective? It scans through each date to ensure that the current date falls within the specified range.

const currentTime = Date.now(); // 2020-10-22T16:35:45+01:00

const dates = [{
    name: "Thomas",
    timeStart: "2020-10-22T16:00:00+0100",
    timeEnd: "2020-10-22T16:15:00+01:00"
  },
  {
    name: "Marc",
    timeStart: "2020-10-22T16:15:00+0100",
    timeEnd: "2020-10-22T16:30:00+01:00"
  },
  {
    name: "Steve",
    timeStart: "2020-10-22T16:30:00+0100",
    timeEnd: "2020-10-22T16:45:00+01:00"
  }
];

// If only one result is needed, use find instead of filter
const validDates = dates.filter((obj) => {
  // Convert strings to Dates
  let startDate = new Date(obj.timeStart);
  let endDate = new Date(obj.timeEnd);
  // Ensure current time is after start date and before end date
  return currentTime >= startDate && currentTime <= endDate;
});

console.log(validDates);

// To retrieve the name, use validDates[0].name (for filter, refer above) or validDates.name (for find)

Answer №3

Here is a suggestion you can try out: filter yourArray based on the condition that currentTime falls within the range of item.timeStart and timeEnd

Answer №4

This is an example of how it could look:

let currentTimestamp = Date.now();

const filteredArray = yourArray.filter(element => {
      // Make sure to convert timestamps for accurate comparison
      return element.startTime < currentTimestamp && element.endTime > currentTimestamp;
      });

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

Disable Button's Shadow when it is in an active state (clicked)

Check out the DEMO to see the button animation CSS in action. The CSS code for the button animations is as follows: .btnliner { /* CSS properties */ } /* More CSS properties */ .btnliner:hover { /* Hover effects */ } Here is the corresponding J ...

Enhancing Password Strength Validation with Formik and Yup in a React Application

I am new to React and currently working on a signup page where I need to validate the password field using Regex. While utilizing Formik and Yup for validations, I encountered an issue where it shows the error that the property being called by the length ...

The slideToggle function in jQuery seems to have trouble working on a Joomla platform, however, it functions perfectly on jsbin

I'm currently working on a website and I'm trying to implement the jQuery slideToggle feature to move some blocks. Everything seems to be working fine when I test the code on jsbin.com, but for some reason, it's not functioning properly on m ...

Choose a cell from a separate column within a React application

Currently, I've been developing a puzzle game using React JS. My goal is to be able to choose one cell in each column, but I haven't been successful in achieving that yet. You can find the code sample here. Any assistance you can provide would be ...

How can I showcase the index of `<tr>` and `<td>` elements in a dynamically generated table

How can I print the index of table rows and data on click in javascript? <html> <head> <title>Table Creation</title> <script language="javascript" type="text/javascript"> function createTable() { ...

Creating a resizable SVG rectangle element with React

Hey, I'm a beginner in Svg and currently learning ReactJs. I have a question that I'm not sure is possible or not. I have an Svg element with its children wrapped inside a g. The g element contains a rect element that I want to make resizable usi ...

Synchronized scrolling and equal height for multiple divs

Looking to create a system similar to GitHub's conflict resolver for my project. I have multiple versions represented by values in columns, and I want to be able to select different values from each column to create a new solution. It's important ...

I would like to modify the text color of a disabled input field

I need to adjust the font color of V1, which is a disabled input field. I want to make it darker specifically for Chrome. Any suggestions on how I can achieve this? https://i.sstatic.net/kioAZ.png Here's my HTML code: <mat-form-field appearance= ...

Developing an interactive selector within the on() event handler

My goal is to utilize the on() event for managing dynamically created code. It functions properly when the selector is hardcoded in the on() event. However, I aim to enable it to select different elements depending on which box they choose. $("body").on( ...

Tips for preventing cursor tooltips from going off the screen

I've been working on creating a popup box that displays text positioned away from an element when the cursor hovers over it. Check out a simplified demo here. Currently, the popup box collapses when it gets close to the bounding box. I'd like it ...

What could be causing my conditional element to flicker during the loading of the route?

Situation: I am working on a webpage that dynamically displays different div elements based on the response received from an Axios request. If the response does not populate the data array called myExpense[], a div with the alert-warning class is shown. Ot ...

Troubles with a Chrome Extension for JSON

I'm currently working on a project to develop a Google Chrome extension and I've encountered an obstacle. I'm experimenting with JSON data (with the intention of integrating it with an API in the future). I have a sample JSON file, successfu ...

After refreshing, Angular route using html5Mode leads to a 'Page Not Found' error page

I have created several Angular routes as illustrated in the code snippet below. app.config(function($routeProvider, $locationProvider, $provide) { $routeProvider .when('/', { templateUrl: 'home.html', controll ...

How do I incorporate Spotify into my mobile app to enable seamless background music playback?

Currently engaged in a mobile app project that utilizes react-native for the frontend and nodeJS for the backend. The main objective is to enable users to seamlessly play Spotify songs directly within the app, even in the background. This enhancement will ...

Creating a validation error in Angular: When a user submits an empty form, radio buttons will be highlighted in red

I have encountered an issue already posted on GitHub regarding this matter, but unfortunately, no solution has been provided yet. You can view the issue here: https://github.com/angular/components/issues/11333 I was wondering if there are any workarounds ...

Guide on how to retrieve additional data from the API by pressing the "Load More" button

Hello, I am working on a project where I aim to display user data from an API called https://reqres.in/api/users?page=(the page number can be 1,2 or more) and present it in an HTML table using JavaScript with promises. Currently, I have successfully popula ...

What is the structure of multi-dimensional arrays in memory?

When working in C, I am aware that I have the ability to dynamically allocate a two-dimensional array on the heap by using the code below: int** someNumbers = malloc(arrayRows*sizeof(int*)); for (i = 0; i < arrayRows; i++) { someNumbers[i] = mallo ...

Utilizing consistent navigationOptions across multiple screens

Currently facing an issue with setting global header styles across multiple screens in my React Native Project. I have followed the instructions provided at https://reactnavigation.org/docs/en/headers.html. However, I encounter a syntax error whenever I a ...

Insert into the associative array without any duplicate values

My aim is to add a new set of product records to an existing associative array, making sure each product is only included once. I came up with the following function, but it seems like too much code for such a simple task. Is there a PHP array function t ...

Performing mathematical operations on arrays extracted from a CSV file

Currently, I am working on performing numerical operations on multiple arrays while extracting data from CSV files. I have the coordinates of a fixed receiver and I also extract the coordinates of heliostats from a CSV file that track the movement of the ...