WhatTimeIsIt();

DateTimeExtensions

tumblr_mtp8l6fwTh1qbh26io1_r1_500A typical problem I face is redundant code across projects. Whenever I see this happening I try to come up with a solution to unify some functionality in a base library, for me that base is Lr.Core.

Today I want to present you my DateTimeExtensions – which are included in Lr.Core and availble for download at NuGet or lrcore.codeplex.com.

The full documentation on the DateTimeExtensions can be found on http://lrcore.codeplex.com/wikipage?title=DateTimeExtensions%20%28Lr%20-%20Lr.Core%29&referringTitle=Documentation, the most recent source is located at http://lrcore.codeplex.com/SourceControl/latest#Lr.Core/Lr.Core/(extensions)/DateTimeExtensions.cs.

Concrete example: “I need to get all mondays and wednesdays in a given range…”

This doesn’t demonstrate all the functions in the Lr.Core DateTimeExtensions, but here’s a concrete example that I had to deal with recently: “Get all mondays and wednesdays in a given range…”

// Set up the range
var range = new DateTimeRange(
   new DateTime(2014, 09, 01),
   new DateTime(2015, 10, 01)
);

// Set up the days I need
var acceptedDays = new List<DayOfWeek>() {
   DayOfWeek.Monday, DayOfWeek.Wednesday
};

// Iterate and filter
return range.GetDays(acceptedDays);

IRange<DateTime>

Essential to some of the DateTimeExtensions is the class IRange<T>, and it’s IRange<DateTime> implementation DateTimeRange. It basically defines a range between an minimum and a maximum DateTime object. One can then test any DateTime object on the range with the method IsInRange(DateTime dateTime).

// Arrange (set up the DateTimeRange object with a minimum of 11/10/1985 and a maximum of 11/10/1986) 
var expected = true; 
IRange<DateTime> range = new DateTimeRange(
 new DateTime(1985, 10, 11), 
 new DateTime(1986, 10, 11)
); 

// Act (execute the IsInRange method on the range object) 
var actual = range.IsInRange(new DateTime(1986, 10, 1)); 

// Assert 
Assert.Equal<bool>(expected, actual);

 

Leave a comment