This content is archived. See latest version here

Last updated: Apr 20 2015

Use the Filter method to filter DateTime and nullable DateTime (DateTime?) fields in a number of ways. Below is a list of use cases and examples illustrating the available methods.

Note: If you cache search results using the built-in caching functionality, you probably do not want to use DateTimeNow in your filters, as the cache key will differ for each search. In those cases, normalize the DateTime value to the closest minute or, at the very least, second.

Existence

To search for documents where a DateTime field has a value, use the Exists method. The below search finds blog posts that have a PublishDate property with a value. The code is similar to the LINQ query Where(x => x.PublishDate.HasValue).

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.PublishDate.Exists());

Like all filters, it can be negated using an exclamation mark (!). In other words, to find all blog posts with no publish date, use the code below.

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => !x.PublishDate.Exists());

Exact match

For exact matching, use the Match method. The below search matches blog posts published exactly 2010-01-01 00:00. It does not match those published on 2009-12-31, 2010-01-01 01:00 or 2010-01-02. The LINQ equivalent is Where(x => x.PublishDate == new DateTime(2010, 1, 1)).

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.PublishDate.Match(new DateTime(2010, 1, 1)));

Matching by range

To find documents whose DateTime field value is within a given range, use the InRange method. The below search matches blog posts published between 2010-01-01 00:00 and 2010-01-02 00:00. The LINQ equivalent is Where(x => x.PublishDate >= new DateTime(2010, 1, 1) && x.PublishDate<= new DateTime(2010, 1, 2)).

C#
var searchQuery = client.Search<BlogPost>()
    .Filter(x => x.PublishDate.InRange(
        new DateTime(2010, 1, 1), 
        new DateTime(2010, 1, 2)));

For convenience, the .NET API also features the GreaterThan, LessThan, Before, and After methods that make range filtering easier for DateTime fields.


Do you have feedback on this documentation? Send an email to documentation@episerver.com. For development-related questions and discussions, refer to our Forums on https://world.episerver.com/forum/