Monthly Archives: March 2012

TimeSpan formatting as extension method C#

Here’s a simple extenstion method to format a TimeSpan object as total number of hours and minutes (HH:MM) wich supports total hours above 24.

namespace YourProject.ExtensionMethods
{
    public static class Extensions
    {
        public static string ToHHMMString(this TimeSpan span)
        {
            int totalHours = (int) span.TotalHours; //truncate decimals
            return totalHours.ToString(“00”) + “:” + span.Minutes.ToString(“00”);
        }
    }  
}

Advertisements