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.

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).

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

TimeRange

Similiar to DateSpan, this struct 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 (2018-10-01):

public void TimeRangeExample()
{
    var tr = new TimeRange(new DateTime(201811), DateTime.Today);
    Trace.WriteLine(tr);
}

This writes out the following output:

Debug Trace:
A duration of 273.00:00:00 between 2018-01-01T00:00:00 and 2018-10-01T00:00:00.

Closing Words

This was a brief article of the two structs DateSpan 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 🔥