ASP.NET format string as date

I have parts of a date, and I want to insert them to SQL server.

How do I format these into SQL Server smalldatetime?
Who is Participating?
Lalit ChandraConnect With a Mentor Commented:
try this

string strdate = y+ "-" + m+ "-" + d;
INSERT INTO Table (datefield) VALUES ( '" + strdate + "')

The safest date format to use is probably yyyy-mm-dd hh:mm:ss, where the hour ranges from 0 to 23.  Some countries use dd/mm/yyyy, some use mm/dd/yyyy; the problem is that these two formats can be confused with one another for the first twelve days of each month.
Alfredo Luis Torres SerranoConnect With a Mentor Development Director / DBACommented:
SqlStatement = "Insert into Table (DateField) Value (Convert(Smalldatetime,'" + D + '/' + M + '/' + y + "',103))"

Hope this helps
Alfredo Luis Torres SerranoDevelopment Director / DBACommented:
The final statement should look like thie:

Insert into YourTable (TheFieldDate) Value (Convert(Smalldatetime,'26/04/1961',103))
BuggyCoderConnect With a Mentor Commented:
if you have these string in your code then create a datetime object out of them as:-

DateTime dt=new DateTime(Convert.ToIn32(Y),Convert.ToIn32(M),Convert.ToIn32(D));

You can also use Int.TryParse to check for null values.
Now You can simply insert this date into your sqlcommand's sqlparameter, which i am sure you know how to do....
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.