What is the best way to extract the upcoming hours from an Array specifically containing night hours?

My task involves working with an array of hours like this:

['10:00:00', '11:00:00', '13:00:00', '14:00:00', '01:00:00']
. The goal is to filter and retrieve all the hours that come after the current time. For example, if the current time is 13:00:00, then only hours greater than or equal to '13:00:00' should be included in the final array.

I attempted to achieve this filtering using the .filter method:

const now = new Date();
const times = [
 '10:00:00',
 '11:00:00',
 '12:00:00',
 '16:00:00',
 '16:30:00',
 '00:00:00',
 '01:00:00',
 '02:00:00',
 '02:30:00',
];
times = times.filter((t) => {
 return new Date(t) > now;
});

Or alternatively:

const currentHour = new Date().getHours();
const times = [
 '10:00:00',
 '11:00:00',
 '12:00:00',
 '16:00:00',
 '16:30:00',
 '00:00:00',
 '01:00:00',
 '02:00:00',
 '02:30:00',
];
times = times.filter((t) => {
 return Number(t.split(':')[0]) > currentHour;
});

However, due to the nature of dates and midnight transitions, the test for including times after midnight fails.

Here is the desired output:

If the time array is as follows:

['10:00:00', '11:00:00', '12:00:00', '16:00:00', '16:30:00', '00:00:00', '01:00:00', '02:00:00', '02:30:00'];

And the current time is 16:00:00, then after filtering, we expect the resulting array to be

['16:30:00', '00:00:00', '01:00:00', '02:00:00', '02:30:00']

Answer №1

If we assume that the array is always sorted, starting with today's times and then continuing with times after midnight:

const schedule = [
    '10:00:00',
    '11:00:00',
    '12:00:00',
    '15:00:00',
    '16:00:00',
    '16:30:00',
    '00:00:00',
    '01:00:00',
    '02:00:00',
    '02:30:00',
]

const currentTime = new Date().toString().match(/\d{2}:\d{2}:\d{2}/)[0]

const startFromIndex = schedule.findIndex((time, index) =>
    time.localeCompare(currentTime) > 0
    || (index && time.localeCompare(schedule[index - 1]) < 0))
// The second condition is necessary in case the array only contains times before the current time on the same day + times after midnight

const filteredSchedule = schedule.slice(startFromIndex)

console.log(`Times after ${currentTime}:`, filteredSchedule)

Answer №2

let currentDate = new Date()
let currentHour = 16//currentDate.getHours()
let currentMinute = 30//currentDate.getMinutes()
const timeSlots=["10:00:00","11:00:00","12:00:00","16:00:00","16:30:00","00:00:00","01:00:00","02:00:00","02:30:00"];

let sliceIndex = null

timeSlots.forEach((slot, index) => {
  let hourSlot = parseInt(slot.split(':')[0])
  let minuteSlot = parseInt(slot.split(':')[1])

  if (hourSlot == currentHour && minuteSlot >= currentMinute || hourSlot > currentHour) {
    sliceIndex = sliceIndex === null ? index : sliceIndex
  }
})

let updatedTimeSlots = timeSlots.slice(sliceIndex + 1)

console.log(updatedTimeSlots)

Answer №3

const times = ['10:00:00', '11:00:00', '12:00:00', '16:00:00', '16:30:00', '00:00:00', '01:00:00', '02:00:00', '02:30:00' ];
let newTimes = times.slice(times.indexOf('16:00:00') + 1, times.length);

In case you want to verify the presence of a specific time in your array, you can store the result of indexOf in a separate variable (if not found, it returns -1).

Answer №4

Due to the limitations of my current time array, I found it impossible to achieve what I was seeking. As pointed out by @lionel-rowe, I struggled with differentiating between "5AM earlier today" and "5AM after midnight tomorrow." This led me to make a change in my database where I switched the date type from Time to string. By doing this, I could now combine all night hours from the next day with morning hours from the same day into one array.

For instance, if the time is 5AM, I store it in the DB as '05:00:00'. When a user wants to input 5AM after midnight, I specify the hour as '29:00:00'. In JavaScript, I simply check if the hour is >= 24, and if true, I set the hour to be day + 1.

The code snippet below illustrates this approach:

const ore = ["01:00:00", "08:30:00", "12:00:00", "12:30:00", "13:00:00", "13:30:00", "14:00:00", "14:30:00", "24:00:00", "25:00:00", "26:00:00"];
const giorno = new Date();
const final = ore.map((o) => {
const hour = o.split(':')[0];
const min = o.split(':')[1];
const date = new Date(giorno);
if (Number(hour) >= 24) {
date.setDate(date.getDate() + 1);
date.setHours(Number(hour) - 24, Number(min), 0, 0);
} else {
date.setHours(Number(hour), Number(min), 0, 0);
}
return date;
})
.sort((a, b) => a.valueOf() - b.valueOf());
console.log(final.toLocaleString());

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

the value contained in a variable can be accessed using the keyword "THIS"

I recently developed a snippet of code that adds a method to a primitive data type. The objective was to add 10 to a specified number. Initially, I had my doubts about its success and wrote this+10. Surprisingly, the output was 15, which turned out to be ...

What are the best techniques for optimizing loops when inserting data into a database?

Hi there! Currently, I am facing a challenge in inserting data from an XML file into my MySql database using Sails.js and waterline for the queries. In my database schema, I have two tables named Users and Pets. A user can have multiple pets, and a pet can ...

What is the best way to validate a value with the help of the $.post functions in JavaScript?

An example of a script: <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> <script type="text/javascript"> $(document).ready( function() { function validateInput( value ) { ...

Utilizing data as a substitute when creating a SearchBar using Vue3

My VueJs3 application has a search bar implemented using .filter(), and it seems to be working fine. However, when I try to pass the value from my methods to the template, an error occurs. My data becomes a proxy and I am unable to use it in that format. ...

Include quotation marks around a string in C# to convert it into JSON format

I am utilizing a service that operates with JSON format. However, the JSON data I am receiving does not include double quotes around keys and values. Here is an example of the data I have: [{name:{buyerfirstname:Randy, buyermiddlename:null, buyerlastnam ...

Do you always need to use $scope when defining a method in Angular?

Is it always necessary to set a method to the $scope in order for it to be visible or accessible in various parts of an application? For example, is it a good practice to use $scope when defining a method that may only be used within one controller? Consid ...

Google-play-scraper encounters an unhandled promise rejection

I'm trying to use the google-play-scraper library with Node.js, but I keep encountering an error when passing a variable as the 'appId'. How can I resolve this issue? Example that works: var gplay = require('google-play-scraper') ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

Sending data from an AJAX request to a Spring controller is a common task in web

var TableDatatablesEditable = function () { var handleTable = function () { function restoreRow(oTable, nRow) { var aData = oTable.fnGetData(nRow); var jqTds = $('>td', nRow); for (var i = 0, ...

What is the best way to rotate an image using AngularJS?

Hey there, I've got an image that I need help rotating. There are two buttons - left and right - that should rotate the image 45 degrees in opposite directions. I attempted to create a directive using the jquery rotate library, but it's not worki ...

Arrange the items in a list in JavaScript in descending sequence

How to sort a list of records in JavaScript in descending order? var number; //dynamic number retrieved from API var test; //dynamic text retrieved from API for (var i; i <= accList.length; i++) { var odlist = 'you have :' + test + number ...

Custom virtual properties can be set in Mongoose by utilizing the return value in a callback function

I've been searching all over for a solution to my issue, but I can't seem to find the right answer. I'm currently using MongooseJS as my ODM and I'm attempting to create virtual getters that can retrieve, process, and display informatio ...

Avoid triggering onClick events on all rows when clicking, aim for only one row to be affected per click

I have a unique situation where I have a table containing rows with a button in each row. When this button is clicked, it triggers an onClick event that adds two additional buttons below the clicked button. The Issue: When I click on a button, the onClick ...

What is the best way to retrieve system information from a properties file and display it on a JSP page before the Javascript code is

As someone who is relatively new to JSPs and their capabilities, I am currently working on developing a suite of 4 separate webapp dashboards, each with its own standalone URL and index.(jsp|html) pages. The backend of these dashboards, which is written in ...

Utilize the input type=date value in the date function to obtain a specific format

How can I pass the value of input type=date to a JavaScript date function? In my HTML code, I have used: <input type=date ng-model="dueDate"> <input type="time" ng-model="dueTime"> <button class="button button-block" ng-click="upload_dueda ...

Tips for Utilizing Environmental Variables within a Vue Application's index.html File

My website has an index file with all the necessary meta tags, stylesheets, and scripts: <!DOCTYPE html> <html lang="en"> <head> <!-- Required Meta --> <meta charset="UTF-8"> <meta http-equi ...

Transitioning from MUI v4 to v5: Issue with declaring module "@mui/styles/defaultTheme"

While working on migrating from MUI v4 to MUI v5 following Material-U's instructions, I encountered the troubleshooting issue where Property "palette", "spacing" does not exist on type 'DefaultTheme.' To resolve this problem, I referred to ...

What steps are needed to have typescript recognize a typed function as a throw-statement?

I'm grappling with a typescript issue - I have a custom function that consistently throws an error, which is used to handle null variables. Strangely, if I directly throw an error without using the function, typescript recognizes that the variable can ...

Press the Enter key to generate a new table row

I have been dynamically creating an HTML table. Each row contains two columns created through a recursive call. Currently, a new row is generated by clicking on the second cell, but I want to switch this action to the "Enter" key press. Although my code su ...

Using an npm package: A step-by-step guide

Recently, I added the following package to my project: https://www.npmjs.com/package/selection-popup I'm curious about how to utilize its features. Can you provide some guidance on using it? ...