Insert into database date with another format

I have a gridview and sqldatasource.

I’m trying to insert new records in database and the Date column type is Date and default format is US , mm/dd/yyyy and I’m trying to insert a date with another format.

  SqlDataSource2.InsertCommand = "Insert into test (Name,Date) VALUES (@Name,@CONVERT(Date,'@Date',104))";
        SqlDataSource2.InsertParameters.Add("Name", nameText);
        SqlDataSource2.InsertParameters.Add("Date", DbType.DateTime, date.Text);

I get: String was not recognized as a valid DateTime.

Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The Date type in format agnostic in the database (unless you store it as a string).

You may first try to get a valid System.DateTime object using DateTime.ParseExact or DateTime.Parse.

Then, set the SqlParameter with this value.

DateTime dateValue = DateTime.Parse(date.Text); // try to make this working first.
SqlDataSource2.InsertCommand= "Insert into test (Name,Date) VALUES (@Name,@Date)";
    SqlDataSource2.InsertParameters.Add("Name", nameText);
    SqlDataSource2.InsertParameters.Add("Date", DbType.DateTime, dateValue);

Method 2

First you should use DateTime object instead of Date.Text, First convert your text into DateTime

Second you don’t need to format date time while inserting if the data type is datatime at SQLServer table just use.

"Insert into test (Name,Date) VALUES (@Name, @Date)";

You should format date time while retrieving data in select


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x