ASP.NET MVC: Helper method to display date ranges

DZone 's Guide to

ASP.NET MVC: Helper method to display date ranges

· ·
Free Resource

I have events web site where I want to show events start and end time to visitors. I wrote simple extension method called DisplayTimeRange() to display event time range on user-friendly manner. My goal is to show times as 01.01.2012 10:00 – 14:00 and 01.01.2012 15:00 – 01.03.2012 18:00. It’s practically displaying time ranges is shortest possible way. In this posting I will show you how to do it using extension method.

For events that happen only on one date I want output like this:

DisplayDateRange(): Event covers only one date

For events that cover more than one date I want output like this:

DisplayDateRange(): Event covers more than one date

Here is my extension method for HtmlHelper. I called it DisplayDateRange and currently it generates output like shown above (styling depends on you).

public static MvcHtmlString DisplayDateRange(this HtmlHelper helper, DateTime from, DateTime to)
    var buffer = new StringBuilder(100);
    buffer.Append(@"<div class=""dateRange"">");
    buffer.Append(" ");
    buffer.Append(" - ");
    if (from.Date == to.Date)
        buffer.Append(" ");
    return new MvcHtmlString(buffer.ToString());

This extension method can be easily extended also to nullable DateTime types if you need it.

DateTime formatting may seem not so perfect but it was the only way how to avoid weird long date and time outputs with seconds (we really don’t need seconds here). If you have good idea about how to format dates shorter in code then feel free to drop me a comment here.


Published at DZone with permission of Gunnar Peipman , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}