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

String To Time In C#

04/18/08

  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,
DateTimeStyles.NoCurrentDateDefault);

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(
DateTime.MinValue));

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-
DateTime.MinValue);

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

March 2019
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            
Ritchie Annand's blog of everything except sports (...and who knows? I may break that rule some day)

Search

  XML Feeds

powered by b2evolution free blog software