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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10625292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:33:56  来源:igfitidea点击:

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

c#datetime

提问by user541597

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

我有以下 C#,它在尝试将字符串解析为日期时间时给了我上面的错误。

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

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

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

Any ideas on how to convert this?

关于如何转换这个的任何想法?

Thanks

谢谢

采纳答案by paulsm4

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

是 - 使用带有自定义格式字符串的“DateTime.ParseExact()”或“TryParseExact()”:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

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)
{
  ...

回答by Austin Salonen

ParseExactshould work for you, assuming your users have no way of editing that value on their own; in that case, you should use TryParseExactto unless you want the FormatException.

ParseExact应该适合您,假设您的用户无法自行编辑该值;在这种情况下,您应该使用TryParseExact,除非您想要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);

回答by Douglas

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).

你的代码看起来是正确的;问题可能与您的字符串格式有关,其最后一个:实际上应该是 a .(表示小数秒的开始)。

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.

Convert.ToDateTime("2012-04-15 15:23:34.123")工作正常。

回答by madeFromCode

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.

您的问题出在 dateTime 字符串的时间部分。如果您的字符串显示为“2012-04-15 15:23:34.123”,则它会起作用。您可以修改字符串并用句点替换最后一个冒号,这样就可以解决问题。

回答by Edward

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.

我已经看到了几个解决此问题中概述的情况的答案,例如使用 DateTime.Parse、DateTime.ParseExact 或 Convert.ToDateTime。我试图确定为什么问题似乎不一致。我使用 Microsoft Enterprise Library Software Factory 和 SQL Server 2008 R2 后端构建了一个应用程序,它已经投入生产大约 9 个月了。它至少有 20 个具有相同代码格式的实例,将 C# 中的 DateTime 属性值分配给存储过程的 System.Data.DBType.DateTime 参数。20 个代码块中的 19 个工作正常。对于 20 日,我不得不添加如下所示的 .ToString() 调用来解决这个问题中提到的错误。

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.

所以有人对为什么它在 19 个完全相同的实例中可以正常工作而不是在 20 个实例中正常工作有一些见解?我只是想更多地了解这些对象的相互关系,以便我可以构建可靠的代码。我已经回到所有其他实例并添加了 .ToString() 调用。还没有完成我的回归测试;所以,我不知道那是不是一个错误。