Time Database Columns in .NET

Overview

With SQL Server 2008 came (among other things), a new data type: time. By default a time field gets imported into Visual Studio as a TimeSpan .NET type. However, the TimeSpan type doesn't format in the familiar way that a DateTime does. This article describes how to format a TimeSpan using the same format string as for a DateTime.

Code

TimeSpan to String

TimeSpan ts = new TimeSpan(14, 43, 00);
DateTime dt = DateTime.Today.Add(ts);
string s = dt.ToString("h:mm tt");

String to TimeSpan

static TimeSpan ParseTimeSpan(string s)
{
    DateTime datum = DateTime.Today;
    TimeSpan result = DateTime.Parse(datum.ToString("MM/dd/yyyy") + " " + s).Subtract(datum);
    return result;
}