Wednesday, March 28, 2012

Saving datetime data in a stored procedure

Hello everyone

I have a stored procedure that I am trying to save datetime data to at the moment I can create a string that will output
25/05/2007 18:30
Does anyone know the best way to get this into the correct format for my SP parameter

cmdPublish.Parameters.Add(newSqlParameter("@.datPublishDate", System.Data.SqlDbType.DateTime));

cmdPublish.Parameters["@.datPublishDate"].Value = ??

Thanks

Use the DateTime.ParseExact( ) method and pass your date value as an argument

ParseExact(Value,Format,FormatProvide) - Format provide can be passed as null and provide the Format value as string of whatever format you want it will return DateTime object which can be assigned to your Parameter

http://msdn2.microsoft.com/en-us/library/w2sa9yss.aspx

|||

If you are doing this from C# there is no "format" you need - you need to use a DateTime variable:

cmdPublish.Parameters.Add("@.datPublishDate", SqlDbType.DateTime ).Value = DateTime.Now;
If you are trying to get some string value from something like a webform, then I would use something like this:
DateTime dt;cmdPublish.Parameters.Add("@.datPublishDate", SqlDbType.DateTime ).Value = ( DateTime.TryParse( yourStringValue,null, System.Globalization.DateTimeStyles.None,out dt ) ) ? (object) dt : (object) DBNull.Value;
You can also use TryParseExact:
cmdPublish.Parameters.Add("@.datPublishDate", SqlDbType.DateTime ).Value = ( DateTime.TryParseExact( yourStringValue,"dd/MM/yyyy hh:mm",null, System.Globalization.DateTimeStyles.None,out dt ) ) ? (object) dt : (object) DBNull.Value;
|||

Thanks for the help - in the end I didn't need to do any of that.
I used
Convert.ToDateTime(str)

and it worked. turned out that there was something ELSE wrong with the SP.

How embarrassing.

ThanksEmbarrassed

No comments:

Post a Comment