该字符串未被识别为有效的DateTime。从索引0开始有一个未知词

use*_*597 4 c# datetime

我有以下C#在尝试将字符串解析为datetime时出现上述错误。

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

imageflowlable.text 看起来像这样 2012-04-15 15:23:34:123

关于如何转换此的任何想法?

谢谢

pau*_*sm4 6

是的-将“ DateTime.ParseExact()”或“ TryParseExact()”与自定义格式字符串一起使用:

http://msdn.microsoft.com/zh-CN/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)
{
  ...
Run Code Online (Sandbox Code Playgroud)