Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The string was not recognized as a valid DateTime. There is an unknown word starting at index 0

Tags:

c#

datetime

I have the following C# that is giving me the error above when trying to parse string to datetime.

DateTime backupdate = System.Convert.ToDateTime(imageflowlabel.Text);   
DateTime currentdate = System.DateTime.Now.AddHours(-2);    
int result = currentdate.CompareTo(backupdate);

imageflowlable.text looks like this 2012-04-15 15:23:34:123

Any ideas on how to convert this?

Thanks

like image 332
user541597 Avatar asked Dec 21 '22 21:12

user541597


2 Answers

Yes - use "DateTime.ParseExact()" or "TryParseExact()" with a custom format string:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.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)
{
  ...
like image 168
paulsm4 Avatar answered Dec 23 '22 11:12

paulsm4


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.

like image 32
madeFromCode Avatar answered Dec 23 '22 11:12

madeFromCode