The title should be self explanatory. I need to index some sitecore items that represent some entities that are valid to the public between certain dates. The sitecore fields are date time fields looking like this.
I needed a solution for indexing these values in a way that i can do range queries on them. I used the UnixTimeStamp for converting the DateTime field in a UnixTimeStamp field.
1 2 3 4 5 6 |
public static string ConvertToUnixTimeStamp(DateTime value) { var date = new DateTime(1970, 1, 1, 0, 0, 0, value.Kind); var unixTimestamp = Convert.ToInt64((value - date).TotalSeconds); return unixTimestamp.ToString(CultureInfo.InvariantCulture); } |
Decoding UnixTimeStamp to DateTime :
1 2 3 4 5 6 |
public static DateTime ConvertToDateTime(double unixTimeStamp) { DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime(); return dtDateTime; } |
The fields would then be indexed as numbers and i could filter the results using a TermRangeQuery on the index like this:
1 |
TermRangeQuery trq = new TermRangeQuery(dateFieldName, UnixTimeStampConverter.ConvertToUnixTimeStamp(startDateTime), UnixTimeStampConverter.ConvertToUnixTimeStamp(endDateTime), true, true); |
I think this solution is quite elegant and easy to use.
Alin Parjolea
System Developer at Pentia. I have been involved in small and large scale projects using Sitecore and .Net for the last 4 years. I am Sitecore certified developer since 2009. I have a Master degree in Computer Science from University of Southern Denmark. More detailed info about me can be found on my Facebook and LinkedIn pages.
- More Posts