Try our conversational search powered by Generative AI!

Loading...
Area: Optimizely Search & Navigation
ARCHIVED This content is retired and no longer maintained. See the latest version here.

Recommended reading 

Introduction

The Filter method can be used 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 that if you cache the search results using the built in caching functionality you probably dont want to use DateTime.Now in your filters as the cache key will then differ for each search. In those cases, instead 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, we can use the Exists method. The below search will find blog posts that has a PublishDate property with a value. In other words, the below 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 instead find all blog posts that does not have a publish date we could use the below code.

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

Exact match

For exact matching we can use the Match method. The below search will match blog posts published exactly 2010-01-01 00:00. It will not match those published 2009-12-31, 2010-01-01 01:00 or 2010-01-02. The LINQ equivalent would be 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 with a DateTime field that has a value within a given range we can use the InRange method. The below search will match blog posts that have been published between 2010-01-01 00:00 and 2010-01-02 00:00. An equivalent in LINQ could be 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 find this information helpful? Please log in to provide feedback.

Last updated: Sep 21, 2015

Recommended reading