2013-11-22 100 views
1

我想將在SQL Server 2008數據庫中以字符串形式存儲的日期轉換爲smalldatetime在SQL Server 2008中將字符串轉換爲日期格式

所保存的字符串格式爲16/12/2007,我想刪除/,取而代之的是 - 得到正確的日期格式,它是16-12-2007

我收到以下錯誤

Conversion from string "16/12/2007" to type 'Date' is not valid.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Conversion from string "16/12/2007" to type 'Date' is not valid.

Source Error:

Line 34: NewsItem.Visible = True
Line 35: NewsItem.Date_Modified = CDate(GetContent.Ndate)
Line 36: NewsItem.Date_Published = CDate(GetContent.Ndate)

我想到的創建一個函數,用-替換/字符,然後更新數據庫,但這需要很長時間。

+1

如果您可以避免將日期作爲字符串存儲在首位,那麼問題就不會出現。 SQL Server具有完全可用的'date'和'datetime2'數據類型,ADO.NET知道如何翻譯.NET .NET DateTime類型。如果您偏離此目的並使用不合適的存儲類型,則只會遇到格式問題。 –

回答

0

從數據庫中檢索日期作爲字符串,然後使用Date.ParseExact將日期和時間的指定字符串表示轉換爲與DateTime等效的日期和時間。

Dim ydate = "16/12/2007" 
Dim edate As Date = Date.ParseExact(ydate, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo) 
1

,如果你真的想存儲datetime/smalldatetime■不要使用字符串。使用sql-parameters來避免本地化/格式問題,以及 - 更重要的是 - 防止sql注入。 VB.NET Date可用於smalldatetime列。使用Date.TryParse來驗證和解析字符串。

Dim sql = "INSERT INTO dbo.TableName(Date_Modified)VALUES(@Date_Modified);SELECT CAST(SCOPE_IDENTITY() AS INT);" 
Using con = New SqlConnection("Connection-String") 
    Using cmd = New SqlCommand(sql, con) 
     Dim dt As Date 
     If Not Date.TryParse(GetContent.Ndate, dt) Then 
      MessageBox.Show("please enter a valid date") 
      Return 
     End If 
     cmd.Parameters.AddWithValue("@Date_Modified", dt) 
     Dim newID = cmd.ExecuteScalar() ' presuming that you have an identity column that is autoincremented 
    End Using 
End Using 
相關問題