I want to see whether an item in my array was created today, so I’m using an arrayFilter to filter each element in my array, the problem is, I can’t get my filter to work properly:
return ko.utils.arrayFilter(self.enquiries(), function (enquiry) {
var include = true;
if (self.onlyToday()) {
var formatted = $.datepicker.formatDate("dd/mm/yy", new Date());
include = include && +enquiry.EnquiryDate.indexOf(+formatted > -1);
}
return include;
});
Here is what my data looks like:
formatted: 26/11/2012
enquiry.EnquiryDate: 08/11/2012 08:46:46
So obviously, this enquiry should be filtered as it wasn’t created today.
There are several problems here.
You’re putting a string in
formatted, then later using+formatted > -1.+formattedwill always beNaN, which is never> -1(it’s also never equal to-1and never< -1).You’re setting
includetotrueand then doinginclude = include && .... The part following the&&will never be evaluated, because the part to the left of&&istrueand JavaScript (like most modern languages) short-circuits expressions.If
enquiryrefers to an object,+enquirywill probably beNaNunless you’ve overridden itsvalueOf.You’re comparing strings, which means the most significant parts of the comparison will be on the left — but your date strings are in a format where the most significant values are on the right. So for example, the string
"01/01/2013"is less than the string"02/02/2012", even though of course that’s not true of the dates they represent. If you want to meaningfully compare date strings, they must have the year on the left, followed by the month, followed by the day.Based on your quoted
enquiry.EnquiryDatestring, you can do this:Notes on the above:
Note that I’m getting today’s date with the year on the left.
I’ve removed the
self.onlyToday()bit because the filter didn’t do anything ifself.onlyToday()was false. My guess is you want that check outside this filter function, and you’re either going to call this filter, or not.Since
enquiry.EnquiryDateis a date and time string, separated with a space, first we split it on a space, then we take the first part (the date) and split it on the/. Then we recombine that inyy/mm/ddorder.Now we know we can do the
===on the strings to see if the enquiry date equals today.You could, of course, do this comparison using
Dateobjects, but as you’d just have to parse theenquiry.EnquiryDatestrings intoDateobjects anyway, and you only want day resolution (not millisecond resolution), using a string compare seems reasonable.