I have the following C# that is giving me the error above when trying to parse string to datetime.
DateTime backupdate = System.Convert.ToDateTime(imageflowl
I have seen several answers to resolve the situation outlined in this question such as using DateTime.Parse, DateTime.ParseExact, or Convert.ToDateTime. I am trying to determine why the problem is seemlingly inconsistent. I built an application using the Microsoft Enterprise Library Software Factory with a SQL Server 2008 R2 backend and it has been in production for about 9 months now. It has at least 20 instances with the same code format that assign DateTime property values from C# to System.Data.DBType.DateTime parameters for stored procedures. 19 of the 20 code blocks work fine. For the 20th I had to add the .ToString() call as shown below to resolve the error mentioned in this question.
db.AddInParameter(command, "beginDT", DbType.DateTime, timeBlock.BeginDT.ToString());
So anyone have some insight on why would it work fine in 19 absolutely identical instances and not in the 20th? I am just trying to get more of an understanding of the inter-relationship of these objects so I can build solid code. I have since gone back to all other instances and added the .ToString() call. Haven't completed my regression testing though; so, I don't know if that was a mistake.
Yes - use "DateTime.ParseExact()" or "TryParseExact()" with a custom format string:
http://msdn.microsoft.com/en-us/library/8kb3ffffd4.aspx
DateTime currentdate;
int result;
try
{
// EXAMPLE: 2012-04-15 15:23:34:123
DateTime backupdate =
DateTime.ParseExact (
"yyyy-MM-dd HH:mm:ss:fff", //mind the casing
imageflowlabel.Text,
CultureInfo.InvariantCulture);
currentdate = System.DateTime.Now.AddHours(-2);
result = currentdate.CompareTo(backupdate);
}
catch (Exception ex)
{
...
Your problem is with the time part of your dateTime string. If your string read "2012-04-15 15:23:34.123" then it would work. You could modify your string and replace the last colon with a period and that would fix it.
ParseExact should work for you, assuming your users have no way of editing that value on their own; in that case, you should use TryParseExact to unless you want the FormatException
.
var toParse = "2012-04-15 15:23:34:123";
var parsed = DateTime.ParseExact(toParse, "yyyy-MM-dd HH:mm:ss:fff", null);
Assert.AreEqual(new DateTime(2012, 4, 15, 15, 23, 34, 123), parsed);
Your code looks correct; the issue is presumably with your string format, whose last :
should actually be a .
(indicating the start of the fractional seconds).
Incorrect: 2012-04-15 15:23:34:123
Correct: 2012-04-15 15:23:34.123
Convert.ToDateTime("2012-04-15 15:23:34.123")
works fine.