简体   繁体   中英

how to filter a js array by date comparison?

I have a js array of objects and each object has a StartDate property. I need to filter the array by date range. Something like this:

const matchesByDate = supplierPricingInfo.filter(x => x.StartDate > Date("12/25/2019"))

I tried the line of code above as well as putting the new keyword in front of the Date constructor. However, this approach doesn't return any results, even though the array has an item with a StartDate of 01/01/2020.

So what would be the proper way to achieve what I'm trying to do here? I'm using the dayjs npm package in my project if that can be used to help simplify things at all.

Javascript doesn't provide the functionality you are trying to achieve in the format you are using. Instead what you can do is use other functions provided by the Date object.

Javascript Date object has a ' getTime ' function that returns the epoch (UNIX Timestamp). You can create a date object from both the dates and get UNIX Timestamp of both of them to compare.

let startDate = new Date("25/10/2019");
let tempDate = new Date("09/02/2020");

let isStartDateGreater = startDate.getTime() > tempDate.getTime();

// isStartDateGreater = false;

In your case, you can do

const matchesByDate = supplierPricingInfo.filter(x => new Date(x.StartDate).getTime() > new Date("12/25/2019").getTime())
var datesArray = [new Date(2019, 11, 26), new Date(2020, 1, 23), new Date(2002, 5, 23)];
var comparisonDateTime = new Date(2019, 11, 25).getTime();
var matches = _.filter(datesArray, d => d.getTime() > comparisonDateTime);
console.log(matches);

You can use the getTime() method to get the universal time and use that as the comparison, and then use the filter method from the underscore library to only return dates with a universal time greater than the universal time you've set. In the example above I created three sample dates and then a comparison time that you will use to filter dates. We then use the filter method and iterate through each date and return it only if its' universal time is greater than the comparison time you've used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM