2013-11-22 101 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 
相关问题