« Expelled! Race-Baiting Hooks A FewFinal Death of an Iconic Restaurant »

String To Time In C#


  04:04:52 pm, by Nimble   , 266 words  
Categories: Thoughts, Programming

String To Time In C#

If you are trying to get a time into a DateTime from a string, it's relatively easy:

DateTime dt = DateTime.Parse(inputText,CultureInfo.CurrentCulture,

The NoCurrentDateDefault is pretty important. Otherwise, if your string contains no date part, the current date will be added on top of your time.

One issue does arise, though, if you are planning on putting this time into a database, since the NoCurrentDateDefault makes the date 1/1/0001, which is actually too small for SQL Server (whose minimum date is 1/1/1753) or COM/OLE purposes (which has a minimum date that seems to vary - DateTime.FromOADate(0) is 12/31/1899 - .NET will let you go lower than 0, but unknown as to whether this is kosher for other applications).

You can at least tell whether your DateTime had a date component... unless they entered 1/1/0001):

bool noDateEntered = dt.CompareTo(DateTime.MinValue.AddDays(1))<0;

If you want to add your time to the minimum for one of the other date/time types, here is a formula that will do it:

dt = dt.Add(System.Data.SqlTypes.SqlDateTime.MinValue.Value.Subtract(

If you want to replace Add and Subtract with operators, make sure that you keep the parentheses around the right hand side, since the addition and subtraction only work with TimeSpans. Otherwise, you will get a type complaint.

dt = dt+(System.Data.SqlTypes.SqlDateTime.MinValue.Value-

Similar for OLE dates:

dt = dt+(DateTime.FromOADate(0)-DateTime.MinValue)

Alas, now I get an even less fun part to do: figure out how to represent a time on its own in a database in a cross-database manner. *sigh*

No feedback yet