Home > Software design >  How to pass datetime input paramter to stored procedure from vb.net application?
How to pass datetime input paramter to stored procedure from vb.net application?

Time:12-03

I'm trying to pass datetime parameter which is in string format to my stored procedure but its throwing me "String to datetime coversion is not valid" error

Vb. net Code

Dim dt As DateTime = DateTime.ParseExact(Trim(RecordDate),"mm/dd/yyyy",CultureInfo.InvariantCulture)
cmd.Parameters.Add("@recdate", Asedbtype.DateTime).Value = dt

Stored proc

Create Procedure sec_edit (
    @recdate datetime
)

Please let me know what i should do to avoid this error

CodePudding user response:

Based on the error "String to DateTime coversion is not valid", the string could not be formatted into a valid DataTime. The lower case "mm" for the month format should be capitalized: "MM". There are several variants for the date time format, example code below.

Dim dateFormat As String() = New String() {"MM/dd/yyyy", "M/dd/yyyy", "M/d/yyyy", "MM/d/yyyy"}
Dim dt As DateTime = DateTime.ParseExact(Trim(RecordDate),dateFormat ,CultureInfo.InvariantCulture)

Refer to help documentation for DateTime formats https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-6.0#System_DateTime_ParseExact_System_String_System_String___System_IFormatProvider_System_Globalization_DateTimeStyles_

CodePudding user response:

try this:

Dim myDateTime = DateTime.Parse(myDTP.Text)
cmd.Parameters.AddWithValue("@date",myDateTime)
  • Related