Ways to verify if the current date exists within a TypeScript date array

I am trying to find a way in typescript to check if the current date is included in a given array of dates. However, even after using the code below, it still returns false even when the current date should be present within the array. Can anyone please provide a solution?

let time1= ['5:00:00 PM','5:59:59 PM'];
const dateCheck = new Date().toLocaleTimeString('en-US');
const status = time1.includes(dateCheck) ?true:false;
console.log(status);

Answer №1

check for an exact match in the array using include, not including between

if you want to check between two times, populate the array with all possible times in between

instead of include, use > >= and < <= for between checks

const dateCheck:date = new Date().toLocaleTimeString('en-US');
const time1:string[] = ['12:00:00 PM','12:59:59 PM'];

const status: boolean = (time1[0]<=dateCheck && time1[1]>=dateCheck)
console.log(dateCheck,status);

//output "12:56:13 PM", true

this method uses alphabetic comparison rather than date comparison, leading to unexpected outcomes; consider converting to timestamps or comparing date components for accuracy

const dateCheck:date = new Date()
const time1 = [{
    hour:12,
  minute:0
},{
    hour:17,
  minute:59
}]

//convert to number of minutes since midnight for numeric comparison
const dayMins = dateCheck.getHours()*60+ dateCheck.getMinutes()
const start = time1[0].hour*60+ time1[0].minute
const end = time1[1].hour*60+ time1[1].minute

const status = (
    dayMins>=start &&  dayMins<=end
)
console.log(dateCheck.toLocaleTimeString(),status)

Answer №2

let times = ['6:00:00 PM', '6:59:59 PM'];

start = new Date('2022-01-01 ' + times[0]).getTime()
end = new Date('2022-01-01 ' + times[1]).getTime()

checkTime = new Date('2022-01-01 ' + '6:30:00 PM').getTime()
const inRange = checkTime > start && checkTime < end;

Answer №3

Many responses here rely on string-based comparisons. For accurate results, it is recommended to use numeric comparisons instead, especially when dealing with different times of the day like between 10PM and 2AM.

function checkTime(timeCheck, timeRange) {
    const datePart = '2000-01-01 ', // anchoring times to the same date
        d0 = new Date(datePart + timeRange[0]).getTime(),
        d1 = new Date(datePart + timeRange[1]).getTime(),
        dToCheck = new Date(datePart + (typeof timeCheck === 'string' ? timeCheck : timeCheck.toLocaleTimeString('en-US'))).getTime();

    if (isNaN(d0) || isNaN(d1) || isNaN(dToCheck)) throw new TypeError('invalid time format');

    return d0 < d1
        ? d0 <= dToCheck && dToCheck <= d1  
        : d1 <= dToCheck || dToCheck <= d0;

}

const timeRange = ['5:00:00 PM','5:59:59 PM'];

checkTime('5:15:00 PM', timeRange); 
checkTime('5:15 PM', timeRange); 
checkTime('5:15:00 AM', timeRange); 
checkTime('5:15 AM', timeRange); 
checkTime(new Date().toLocaleTimeString('en-US'), timeRange); 

If you need to perform this check for multiple items, utilizing currying can enhance performance by pre-calculating the comparison range.

function buildCheckTime(startTime, endTime) {
    const datePart = '2000-01-01 ', 
        d0 = new Date(datePart + startTime).getTime(),
        d1 = new Date(datePart + endTime).getTime();

    if (isNaN(d0) || isNaN(d1)) throw new TypeError('invalid time format');

    return d0 < d1
        ? function(timeCheck) { 
            const dToCheck = new Date(datePart + (typeof timeCheck === 'string' ? timeCheck : timeCheck.toLocaleTimeString('en-US'))).getTime();

            if (isNaN(dToCheck)) throw new TypeError('invalid time format');

            return d0 <= dToCheck && dToCheck <= d1;
        }
        : function (timeCheck) { 
            const dToCheck = new Date(datePart + (typeof timeCheck === 'string' ? timeCheck : timeCheck.toLocaleTimeString('en-US'))).getTime();

            if (isNaN(dToCheck)) throw new TypeError('invalid time format');

            return d1 <= dToCheck || dToCheck <= d0;
        }
}

const checkTime = buildCheckTime('5:00:00 PM','5:59:59 PM');

checkTime('5:15:00 PM'); 
checkTime('5:15 PM'); 
checkTime('5:15:00 AM'); 
checkTime('5:15 AM'); 
checkTime(new Date().toLocaleTimeString('en-US')); 

Answer №4

let startTime = ['5:00:00 PM','5:59:59 PM'];
const currentTime = new Date().toLocaleTimeString('en-US');
const isValidTimeRange = startTime[0] < currentTime && startTime[1] > currentTime;
console.log(isValidTimeRange);

Instead of using includes, you can use the indexOf function to check for an exact match within an array.

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

Click on the div in Ionic 2 to send a variable

<div class="copkutusu" (click)="kanalsil(kanalid,deneme)" #kanalid id={{ver.channelid}} #deneme id={{ver.channelapikey}}></div> I am requesting kanalid.id and deneme.id in my .ts file. Even though they are the same variable names, they repres ...

JavaScript code to remove everything in a string after the last occurrence of a certain

I have been working on a JavaScript function to cut strings into 140 characters, ensuring that words are not broken in the process. Now, I also want the text to make more sense by checking for certain characters (like ., ,, :, ;) and if the string is bet ...

Is there a method to ensure the strong typing of sagas for dispatching actions?

Within redux-thunk, we have the ability to specify the type of actions that can be dispatched enum MoviesTypes { ADD_MOVIES = 'ADD_MOVIES', } interface AddMoviesAction { type: typeof MoviesTypes.ADD_MOVIES; movies: MovieShowcase[]; } typ ...

The concept of TypeScript usage within the `mui-x` DataGrid while calling the `useGridApiRef()` function

Could someone please help me understand the syntax used in this code snippet from mui/mui-x? export declare const useGridApiRef: <Api extends GridApiCommon = GridApiPro>() => React.MutableRefObject<Api>; My interpretation is that it exports ...

Initializing the $(this) variable prior to the function declaration

I am faced with the task of performing multiple checks based on the IDs of certain elements, all of which vary slightly. So, I created several functions to handle this, and rather than repeatedly using $(this).children ..., I wanted to create a short vari ...

Send a query to Express as a parameter

Currently, I have implemented an ejs file that contains a table element with clickable rows defined as follows: <tr onclick="myFunction(this)"> To pass a query parameter in an http request using javascript, I have the following code snippe ...

What is the most effective approach to building this function in React JS rather than the existing .map method?

Hello, I'm fairly new to all of this so please bear with me. I've been working on developing a search function for my app, but I've encountered a problem. The search function in my header component is being rendered like this in my index: &l ...

Tips for Decreasing Query Time with MatTable and MatTableDataSource

When working with my firestore database, I am trying to query documents and display them while also calculating the total value of a specific column (promiAmount). I have successfully displayed the values in a mat table, but I'm struggling to calcula ...

The Freemode feature in SwiperJS is not functioning properly when used with React TypeScript

Having a slight issue with SwiperJS. Using version 10.1.0 and the following code : import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; export default function Discover() { return ( <> ...

Exploring the power of Jade and Angular through implementing a for loop within a table structure

I'm brand new to using Jade and Angular, and I could really use a hint from someone more experienced. ... - for (var i = 0; i < p.length; i++) tr td= i + 1 td= price(value='p[i].somedbstuff') ... I want the la ...

Step-by-step guide to implementing a user-friendly search input field using the powerful AngularJS material design framework

I am searching for an effortless method to implement a feature similar to the expandable search text field in angular-mdl. By clicking on a search button, it will expand into a text field. <!-- Expandable Textfield --> <form action="#"> < ...

The Rails base file contains a function, let's call it function A, which calls another function, function C. However, function C is defined in two separate JavaScript files

My project includes an application_base.js file with a function: function drawLocations(canvas, blag, blah) { //do some stuff selectLocations(a_something, b_something); //do some stuff } For Page 1: page_1.js function selectLocations(a_somet ...

I noticed that my API call is being executed twice within the router function

In my NextJs project, I am utilizing Express for routing. I have implemented a router with a dynamic :id parameter which triggers an axios call to check the ID in the database. However, I am facing an issue where the API is being called twice when the :id ...

What are the steps to troubleshoot server-side TypeScript code in NextJS with WebStorm?

I am struggling to debug the NextJS API in WebStorm while using TypeScript and navigating through the app route. It is proving to be quite challenging to efficiently debug the API without relying heavily on console.log(). ...

Exploring Angular 4's capability: Incorporating data from Http Post Response into a .js file or highchart

I'm a beginner with Angular 4. I'm trying to create a dashboard that pulls data from an Http Post Response and I want to use this data to create a Chart (Highchart). I have successfully received the response in the console.log and formatted it i ...

Just a straightforward Minimum Working Example, encountering a TypeScript error TS2322 that states the object is not compatible with the type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

Currently, I am immersed in a project involving React and Typescript. I am grappling with error code TS2322 and attempting to resolve it. Error: Type '{ submissionsArray: SubmissionProps[]; }' is not assignable to type 'IntrinsicAttributes ...

Encountering issues with retrieving application setting variables from Azure App Service in a ReactJS TypeScript application resulting in '

My dilemma lies in my app setup which involves a Node.js runtime stack serving a ReactJs Typescript application. I have set some API URLs in the application settings, and attempted to access them in ReactJs components using process.env.REACT_APP_URL, only ...

The Issue of Double-Clicking on Table Cells in Internet Explorer 8

I implemented a JQuery function to add a double click event listener to a table, which triggers a modal popup when a cell is double-clicked. While this functionality works seamlessly in Firefox, there is an issue in IE8 where double-clicking a cell highli ...

What could be causing the multifiles uploader to fail in uploading files?

I have been attempting to create a multiple files uploader with sorter connected to a database on my website. However, whenever I try to upload some files, the uploader sends me several notices. Notice: Undefined index: media in /var/www/mediasorter/mediau ...

Guidelines for Nestjs class-validator exception - implementing metadata information for @IsNotIn validator error handling

I have a NestJs data transfer object (dto) structured like this import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator'; import { AppService } from './app.service'; const restrictedNames = ['Name Inc', 'Acme Inc&ap ...