What method can we use to verify if an object falls within a specified date range when filtering?

Looking to determine if the current filter object falls within a specific date range and return a boolean value based on that condition. However, the code provided always returns the data. Can anyone spot the error in the implementation or suggest a better approach to achieving this task?

main.ts

 function mapResponse() {
    let _startDate = "2018-12-15";
    let _endDate = "2019-01-15";
    _startDate = moment.utc(_startDate || twentyfourMonthsAgo, ["YYYY-MM-DD",  "MM-DD-YYYY", "MM/DD/YYYY"]).format("YYYY-MM-DD");
    _endDate = moment.utc(_endDate || today, ["YYYY-MM-DD",  "MM-DD-YYYY", "MM/DD/YYYY"]).format("MM/DD/YYYY");
    const response = [
            {
                rxNumber: "15139",
                rxIssueDate: "",
                fillDate: "2019-01-03",
                quantityRemaining: "3",
                prescribedNoOfRefills: "3",
                currentFillNumber: "0"
            },
            {
                rxNumber: "16131",
                rxIssueDate: "",
                fillDate: "2019-12-03",
                quantityRemaining: "3",
                prescribedNoOfRefills: "3",
                currentFillNumber: "0"
            }
        ]

        response = response.filter(
            function renameSpecialtyAttributesToPBM(specialtyRx: any) {
                const mappedRx = specialtyRx as Partial < any >;

                const dateFilter = checkDateRange(_startDate, _endDate, specialtyRx.fillDate);

                if (!dateFilter) {
                    return false;
                }

                mappedRx.fillDate = specialtyRx.fillDate;

                mappedRx.refillEligible = !!mappedRx.refillStatusText;
                mappedRx.renewEligible = !!specialtyRenewStatus;

                return true;
            });


    }
      return response;
}

checkDateRange.ts

function checkDateRange(startDate: any, endDate: any, fillDate: RxDetailsEntity): boolean {
    if (fillDate > startDate && fillDate < endDate) {
        return true;
    }

    return false;
}

Expected output from mapResponse:

response = [
                {
                    rxNumber: "15139",
                    rxIssueDate: "",
                    fillDate: "2019-01-03",
                    quantityRemaining: "3",
                    prescribedNoOfRefills: "3",
                    currentFillNumber: "0"
                }]

Answer №1

It appears that the issue lies in passing string dates to your date comparison function and using less than/greater than operators. This can cause problems in the comparison process.

If you prefer a more traditional approach, you can compare dates by converting them to timestamps like this:

checkDateRange(startDateString: string, endDateString: string, fillDateString: string): boolean {
    const startDate = new Date(startDateString).getTime();
    const endDate = new Date(endDateString).getTime();
    const fillDate = new Date(fillDateString).getTime();
    if (fillDate > startDate && fillDate < endDate) {
        return true;
    }

    return false;
}

The getTime() method of the native JavaScript Date class provides the timestamp of the date since the Unix epoch, allowing for numerical comparison of dates.

If you are working with Moment.js dates, you can utilize Moment's isBetween method for date comparisons:

const fillDate = moment(fillDateString).utc();
return fillDate.isBetween(_startDate, _endDate);

Answer №2

Transform the dateStrings into a valid date object. Next, utilize the getTime() function on those dates to obtain the unix timestamp number. This will enable you to determine if any of the dates fall within a specified start and end date range.

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

Tips for repairing a side bar and header with CSS when using a JS & jQuery scroller

I am working on a layout design and my goal is to have the left sidebar, right sidebar, and header remain fixed in place. Here is the CSS code I am using : #container { padding-left: 200px; /* Left Sidebar fullwidth */ padding-ri ...

The Redux Store seems to be holding onto the initial state and not updating, even though the actions are functioning correctly

Upon successful authentication, the actions and reducer are updating correctly, but the mapstatetoprops function is not reflecting the changes in the new reducer state. Despite updates, the Store continues to log the initial state with each update. impor ...

Creating a completely dynamic button in Angular 6: A step-by-step guide

I have been working on creating dynamic components for my application, allowing them to be reusable in different parts of the program. At this point, I have successfully developed text inputs that can be dynamically added and customized using the component ...

In JavaScript, the elements within document.forms[0] are distinct from those within document.<formname>

In my attempt to incorporate client-side validation in Struts 2 with the xhtml theme, I have encountered an issue. The JavaScript being generated is unable to validate my code. Upon further investigation, I discovered that Struts is using a specific notati ...

Angular 2: Dealing with Missing Image Loading

When viewing an HTML file containing the following code: <div> <img src="New-Google-Logo.png"/> </div> The image file New-Google-Logo.png is expected to load from the same folder as the HTML file. However, after running ng s ...

Displaying JSON with AngularJS HTTP Get request won't work in my project

As I delve into the world of AngularJS, I find myself caught up in a puzzle that has consumed my entire evening. My goal is to fetch JSON data from a random generator and display it in the view using a service. While {{ main.title }} seems to be working ju ...

Angular applications can redirect to their own internal pages when linking to an external URL

I've recently started using Angular and have encountered a minor issue. My routing setup is working as expected in the navbar, but I have a link that points to an external URL. When I click on it, instead of redirecting me to the external site, it ta ...

Refresh the dataTable following the form submission within the colorbox

On my page test.php, I am using jQuery DataTables to fetch data. There is a button labeled "Add Note" that opens an ajax form inside colorbox. The form submission process is functioning correctly, but I am looking for a way to refresh the DataTables when a ...

Unexpected behavior with Bootstrap classes

I have come across the following HTML code which appears to be using bootstrap, however, it is not responsive. It is supposed to be responsive and adapt to mobile and tablet devices, but it still displays the desktop view on mobile and tablet screens. < ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...

Utilizing WebPack 5 in conjunction with Web workers in a React/Typescript environment

Can someone help me figure out how to make a web worker function properly with create-react-app, Typescript, and Webpack 5? I've been struggling with limited documentation and can't seem to find a clear explanation. I'm trying to avoid using ...

Issues with Skrollr JS on mobile device causing scrolling problem

Currently facing an issue with Skrollr js. It is functioning perfectly in web browsers and mobile devices. However, there seems to be a problem when tapping on a menu or scrolling down arrow as it does not initiate scrolling. Assistance would be greatly ...

Is there a way to alter the format of a URL?

I'm utilizing the ytdl-core library to access a URL for audio content. The provided URL is: https://r2---sn-gwpa-w5py.googlevideo.com/videoplayback?expire=1612552132&ei=ZEMdYNnJDumPz7sPyrSLmAw&ip=49.36.246.217&id=o-AFQLS1cSUJ6_bXBjMOIiWk1N ...

Is there a way to carry out tests on keydown events within Jasmine by specifying the keyCode within an Angular2+

I am working on a project where I need to trigger keydown events on an <input> field. Tools Used Karma v1.7.1 as the test runner Tests running on Chrome browser Using Angular 5 framework Any insights on how I can achieve this? ...

Adjust date by one day using the Datetimepicker tool

I have been attempting to adjust the date of my input by one day either forward or backwards, but I seem to be stuck and not making any progress. Take a look at my code: function function backDay() { var date = $('input#datetimepicker').va ...

How can XML data be effectively showcased on a website?

I have a service that generates XML files every 10 seconds with server information. I am seeking a solution to showcase this data on a webpage. After researching online, it appears that utilizing AJAX would be beneficial as it permits the loading of dynam ...

It is not possible to transfer information to a JSON document using node.js filesystem and browserify

In an attempt to convert incoming input data from a form into JSON format for storage without a backend, I am exploring the use of Node.JS module "fs" or "file-system". To make this work in a browser environment, I am using Browserify for bundling as it r ...

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

parallax scrolling can be a bit bumpy

While working on a website, I've incorporated a slight parallax effect that is functioning almost perfectly. However, I've noticed that the foreground divs tend to jump a little when scrolling down the page. At the top of the page, there is a di ...

Encountering a ReactJS error when retrieving an object assigned from an axios call to an

The code snippet below is causing me some confusion: import React, { Component } from 'react'; import axios from 'axios'; class Dashboard extends Component { state = { name : 'randomname', apiData: {} ...