![](/img/trans.png)
[英]FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0
[英]The string was not recognized as a valid DateTime. There is an unknown word starting at index 0
我有以下 C#,它在嘗試將字符串解析為日期時間時給了我上面的錯誤。
DateTime backupdate = System.Convert.ToDateTime(imageflowlabel.Text);
DateTime currentdate = System.DateTime.Now.AddHours(-2);
int result = currentdate.CompareTo(backupdate);
imageflowlable.text
看起來像這樣2012-04-15 15:23:34:123
關於如何轉換這個的任何想法?
謝謝
是 - 使用帶有自定義格式字符串的“DateTime.ParseExact()”或“TryParseExact()”:
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)
{
...
您的問題出在 dateTime 字符串的時間部分。 如果您的字符串顯示為“2012-04-15 15:23:34.123”,那么它將起作用。 您可以修改字符串並用句點替換最后一個冒號,這樣就可以解決問題。
你的代碼看起來是正確的; 問題可能與您的字符串格式有關,其最后一個:
實際上應該是.
(表示小數秒的開始)。
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")
工作正常。
ParseExact應該適合您,假設您的用戶無法自行編輯該值; 在這種情況下,除非您想要FormatException
,否則您應該使用TryParseExact 。
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);
我已經看到了幾個解決此問題中概述的情況的答案,例如使用 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());
那么有人對為什么它在 19 個完全相同的實例中運行良好而不是在 20 個實例中運行良好有一些見解? 我只是想更多地了解這些對象的相互關系,以便我可以構建可靠的代碼。 我已經回到所有其他實例並添加了 .ToString() 調用。 還沒有完成我的回歸測試; 所以,我不知道那是不是一個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.