Extract Date part and pass only Date
-
I am running into a peculiar problem. I want to extract only date part from DateTime and pass the Date as DateTime datatype to stored procedure. I tried with the following code:
DateTime datetime = DateTime.Now.Date;
Console.WriteLine("Date is : " + datetime);This is always returns with date and time as
4/27/2013 12:00:00 AM
. I want only date, no time and should pass this as Date Datatype. Even though I tried with lots of examples, I am able to do it if I convert to string which is not possible. Is there any way which I can achieve this? Am I doing something wrong here?
-
I am running into a peculiar problem. I want to extract only date part from DateTime and pass the Date as DateTime datatype to stored procedure. I tried with the following code:
DateTime datetime = DateTime.Now.Date;
Console.WriteLine("Date is : " + datetime);This is always returns with date and time as
4/27/2013 12:00:00 AM
. I want only date, no time and should pass this as Date Datatype. Even though I tried with lots of examples, I am able to do it if I convert to string which is not possible. Is there any way which I can achieve this? Am I doing something wrong here?
Look at the name of the structure you're using: DateTime The time component is not optional there. It will always have a time because the value for 12:00 AM is 0. There is no Date structure or class in .NET. If you want to pass the date to a stored procedure, pass in a DateTime to a parameter of a parameterized query. When SQL evaluates a date, the time is still there even though it's not specified. Guess what time it is if it's not specified? Yeah, 12:00 AM. You're basically trying to do something that you don't really need to do at all. If you pass a DateTime into a, for example, SqlParameter object and the parameter type is defined as an SqlDbType.Date, the conversion is done automatically.
A guide to posting questions on CodeProject[^]
Dave Kreskowiak -
I am running into a peculiar problem. I want to extract only date part from DateTime and pass the Date as DateTime datatype to stored procedure. I tried with the following code:
DateTime datetime = DateTime.Now.Date;
Console.WriteLine("Date is : " + datetime);This is always returns with date and time as
4/27/2013 12:00:00 AM
. I want only date, no time and should pass this as Date Datatype. Even though I tried with lots of examples, I am able to do it if I convert to string which is not possible. Is there any way which I can achieve this? Am I doing something wrong here?
Besides the prior comment you should also be aware that MS SQL Server only has one data type 'Date' which only holds a date component. If the database has a different data type then it will ALWAYS have a time component regardless of what you want. You might treat it like it doesn't, with care, but you better understand exactly how values go into and what impact timezones might have.