We all know the two value types DateTime and TimeSpan.

With this article, I will write about two simple (yet, very neat) value types, that has been part of the Cuemon family for a very long time (pun intended) and supplement the above mentioned almost to perfection; they are DateSpan and TimeRange.

After the v.6.0.0 release of Cuemon for .NET, TimeRange was changed to a class an renamed to DateTimeRange that inherits from the abstract class named Range{T}. Also, the former TimeRange was added - but covering a range between two TimeSpan value types.

DateSpan

With this struct I was aiming for a simple way to calculate the interval between two DateTime values. Although it seemed like a simple task, it was not without challenges as I had to think about CultureInfo and Calendar at the same time.

Just looking through the code while writing this, I am sure I would refactor most, as it dates back to 2010 (with some modifications over the years).

Update: the code was refactored with the release of Cuemon for .NET v6.0.0 🎉

Anyway, here is a sample on how to calculate the interval from January 1st this year up till today (2018-10-01):

public void DateSpanExample()
{
    var ds = new DateSpan(new DateTime(201811), DateTime.Today);
    Trace.WriteLine($"{ds.Years} year");
    Trace.WriteLine($"{ds.Months} months");
    Trace.WriteLine($"{ds.GetWeeks()} weeks");
    Trace.WriteLine($"{ds.TotalDays} days");
    Trace.WriteLine($"{ds.TotalHours} hours");
    Trace.WriteLine($"{ds.TotalMinutes:N0} minutes");
    Trace.WriteLine($"{ds.TotalSeconds:N0} seconds");
}

This writes out the following output:

Debug Trace:
0 year
10 months
40 weeks
273 days
6552 hours
393.120 minutes
23.587.200 seconds

DateTimeRange

Similiar to DateSpan, this class also represents a period of time between two DateTime values. However, the representation is pure and does not contain any code that can perform complex calculations as the case is with the DateSpan counterpart.

Here is a sample on how to define a period of time ranging from January 1st this year up till today (2021-05-03):

public void DateTimeRangeExample()
{
    var dtr = new DateTimeRange(new DateTime(202111), DateTime.Today);
    Trace.WriteLine(dtr);
}

This writes out the following output:

Debug Trace:
A duration of 122.00:00:00 between 2021-01-01T00:00:00 and 2021-05-03T00:00:00.

TimeRange

Similiar to DateTimeRange, this class represents a period of time between two TimeSpan values.

public void TimeRangeExample()
{
    var tr = new TimeRange(TimeSpan.FromHours(4), TimeSpan.FromHours(6));
    Trace.WriteLine(tr);
}
Debug Trace:
A duration of 00.02:00:00 between 04:00:00 and 06:00:00.

Closing Words

This was a brief article of the struct DateSpan and the two classes DateTimeRange and TimeRange. I hope it brought something to mind and that you can see the value it might add to your projects.

Never the less; code with passion 🔥