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

Achieving the incorporation of multiple components within a parent component using Angular 6

Within parent.component.html The HTML code I have implemented is as follows: <button type="button" class="btn btn-secondary (click)="AddComponentAdd()">Address</button> <app-addresse *ngFor="let addres of collOfAdd" [add]="addres">< ...

Passing variables in Redirect() without exposing them in the URL; a methodical approach

After scouring the depths of the internet, I have been on a quest to figure out how to seamlessly redirect to a new page on my site while discreetly passing a variable without exposing it in the URL like so: www.test.com/?variable=dont.want.this.here I a ...

Reload Popup Box

I am currently developing a website using Django and I am in need of a popup window that can display logging messages and automatically refresh itself every N seconds. In order to achieve this, I am utilizing the standard Python logger, JavaScript, and Daj ...

Top method for detecting errors in Models? (Node.js + Sequelize)

Looking for a straightforward method to catch errors in an API using Node.js and Sequelize models? Take a look at this code snippet which utilizes async-await: const router = express.Router() const { Operations } = require('../models') router.po ...

Tips for troubleshooting Grunt in PHPStorm (or WebStorm)

Looking for tips on debugging grunt, such as using an event listener function, in PHP Storm. Does anyone have any ideas? I know that PHP Storm has Node.js support, but I'm not sure how to configure debug settings for debugging a grunt task. For examp ...

Oops! An issue has occurred where I am unable to access certain properties (specifically 'Symbol(__APOLLO_CONTEXT__)') while utilizing the Apollo provider

When attempting to implement a query in my upcoming app, I encountered an error that reads: Error: Cannot read properties of undefined (reading 'Symbol(APOLLO_CONTEXT)') This is the setup of my Apollo client: import { ApolloClient, InMemoryCache ...

Utilize Node.js to traverse an array of objects and extract particular values to create a separate array

Looking to extract scores from the ratings array for each object and compile them into a new array. For instance, for post with post_id: "5e1223c2383ce049d8b32eb5", the associated array should be [1, 4]. And for the post with post_id "5e146b993dde720850c1 ...

Using Angular and nativeElement.style: how to alter cursor appearance when clicked and pressed (down state)

I am working with a native elementRef CODE: this.eleRef.nativeElement.style = "_____?????_____" What should go in "???" in order to apply the :active style to the element? (I want to change the cursor style when the mouse is clicked down, not when it is ...

Utilizing Vue.js to ensure that nested components remain within the parent component even when the store

I have been working on a chat messaging system, where I initially populate the store with root messages and then map the state of that list (array). Everything works fine when posting a new message - the store updates and displays the new post. However, I ...

How come the values keep appearing without any loops or subsequent calls being made to the PHP file?

Here is a demo example showcasing 'Server Sent Events(SSE)': Embed HTML code(index.html) : <!DOCTYPE html> <html> <body> <h1>Receiving server updates</h1> <div id="result"></div> <script> if(type ...

Identify when a request is being executed using AJAX by checking the URL

My current code includes multiple ajax requests from various JavaScript files. I am looking for a way to identify specific ajax requests and interrupt their execution in order to prioritize a newer one. Is it possible to detect and stop ajax requests based ...

What is the best way to display index.ejs when the input field is blank?

If the input field is left empty when I click the form button, I want to redirect to "/". After clicking the button, the desired URL should be: http://localhost:3000 Header.ejs <form action="/search" method="GET"> < ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...

The option chosen from the ng-options does not remain attached to the drop-down menu

I need some help with AngularJS as I am still getting the hang of it. Take a look at this not-so-pretty page: This page allows users to add new beers, and each beer can have multiple styles. Clicking 'Add' creates a new dropdown for selecting a ...

Executing invisible reCAPTCHA2 in Angular 6: A step-by-step guide

Recently, I have been trying to implement an invisible captcha into my website. In order to achieve this, I turned to the guidance provided by Enngage on their ngx-captcha GitHub page: https://github.com/Enngage/ngx-captcha While following the instruction ...

What could be causing this issue to not function properly in JavaScript?

Here is a JavaScript code snippet that I am working on: var inx=[2,3,4,5]; var valarray=[]; for (i=0; i<inx.length; i++) { valarray[i]==inx[i]; } for (i=0; i<inx.length; i++) { var posi=inx.indexOf(3); var valy=valarray[posi-1]+1; v ...

How can you merge the class attribute with the ng-class directive based on boolean values?

In my custom directive's link function, I have the following code that dynamically generates a map using d3... map.append("g") .selectAll("path") .data(topojson.feature(counties, counties.objects.counties).features) .enter() .append("path") .attr("d" ...

What is the best way to implement asynchronous guarding for users?

Seeking assistance with implementing async route guard. I have a service that handles user authentication: @Injectable() export class GlobalVarsService { private isAgreeOk = new BehaviorSubject(false); constructor() { }; getAgreeState(): Obser ...

Navigating through pages: How can I retrieve the current page value for implementing next and previous functions in Angular 7?

Greetings, I am a new learner of Angular and currently working on custom pagination. However, I am facing difficulty in finding the current page for implementing the next and previous functions. Can anyone guide me on how to obtain the current page value? ...

Concealing the nearest object

I am currently working on using jquery to hide certain content on a website's index page. Within the fiddle, there is commented out code which I have been experimenting with - however, it hides all content divs if any toggle link is clicked. HTML & ...