Filter by date range, with custom date field

I understand how to filter pages by a date range:

  Site()->children()->find('invoices')->children()->listed()->filterBy('date', '>', '2020-05-6')
  ->filterBy('date', '<', '2019-04-5');

But I can’t work out the syntax for filtering using a custom date field

Explain custom date field… is it really a text field and youve manually entered, or is it a full blown custom datepicker type thing?

ah sorry, I just mean a normal simple date field.

ok, and what does the filter need to do? Looks like it invoices so what is it, future, past, unpaid… whats the criteria?

I need the filter to show invoices between the current tax year. The invoices have a paidDate field to record where paid.

I think this should work, but it does not?

$paid =  site()->children()->find('invoices')->children()->listed()->filter(function ($child) {
	    return $child->paidDate()->toDate() < '2020-05-6' && $child->paidDate()->toDate() > '2019-04-5';
	  });
1 Like

todate() converts to a full blown unix time stamp, so to filter on it, you need ‘2020-05-06’ also as a time stamp i think.

strtotime('2020-05-6')

Give this a shot…

$paid =  site()->children()->find('invoices')->children()->listed()->filter(function ($child) {
  return $child->paidDate()->toDate() < strtotime('2020-05-6') && $child->paidDate()->toDate() > strtotime('2019-04-5');
});

if it doesnt work, var_dump $child->paidDate()->toDate() and reformat ‘2020-05-6’ to match it.

1 Like

that’s it!, cheers :slight_smile:

Just for a bit of background information:

In Kirby 2, a date field called date was a special field. This difference between a date field called date and a date field called whatever, doesn’t exist anymore. To turn a date field into a date in Kirby 3, you use the toDate() method on any date field, either without a date format to get a Unix timestamp, or with a format to get a formatted date.

The first example you posted above

Site()->children()->find(‘invoices’)->children()->listed()->filterBy(‘date’, ‘>’, ‘2020-05-6’)
->filterBy(‘date’, ‘<’, ‘2019-04-5’);

should therefore also work with any date field no matter its name, as long as you use the same date format that is stored, so with two digits for the day, I guess.

1 Like