Cannot pass date into stored procedure - c#

Trying to pass date into a stored procedure as follows:
#dateRegistered = '28/04/2012'
But it keeps telling me:
Error converting data type varchar to date.
It works if I do it as:
#dateRegistered = '04/28/2012'
But this is not the format I want to use.
I have run the following query to set the format:
SET DATEFORMAT dmy
Why isn't it working?
Edit: Here is how I did it:
In my stored procedure, I put:
SET DATEFORMAT dmy
Then from code, I pass it as:
myCommand.Parameters.Add("#dateRegistered", SqlDbType.Date);
myCommand.Parameters["#dateRegistered"].Value = DateTime.Now.ToString("dd/mm/yyyy");
I passed it as string to ensure that even if my computer (or the server) has a different date format, it will always use dmy.
Edit Edit:
I passed it as datetime.now. It seems to transform it to the default format when I send it, and then transform it back to my computer format when I read it. Unsure how exactly this happens, but it seems to be working fine.

It looks like the parameter is a date (in the database), while you try to pass a string (which corresponds to varchar in the database). If you instead pass a .NET DateTime object it should work as expected.

Save yourself the headache and use an unambiguous date format - 20120428 (YYYYMMDD) or 2012-04-28.
As an aside: you mention you're using C# (based on the tags) - how are you using ADO.NET? Or is it Linq to SQL / EF / some other ORM?
Edit:
Ok, use the CONVERT function with an appropriate parameter indicating the format of your date string
EG:
declare #D datetime
set #D = CONVERT(datetime, '04/28/2012', 101)
print #D
101 is US standard format mm/dd/yyyy.
Using convert will ensure it ALWAYS works regardless of any environment settings such as the date order.

If you call set dateformat dmy, that only affects the current connection. You'd have to set it every time right before you convert the string to a date.
The best solution is probably the ISO format, like #IanYates suggests.

dear your code is working after using
* SET DATEFORMAT dmy
because you are passing date as "dd/MM/yyyy"
like "DateTime.Now.ToString("dd/mm/yyyy")"
check the date format in your database by following command :-
dbcc useroptions
and check "dateformat : mdy" by default. So passing your date in "MM/dd/yyyy" format will also work fine.
Happy Coding :)

Related

Formatting sql datetime to MM/dd/yyyy using C#

I have a date stored in SQL. When I get the value back I want to format as MM/dd/yyyy, but I'm getting values like 2020-09-01 instead.
AccountHolderRenewalDate = a.AccountRenewalDate.ToString("MM/dd/yyyy")
Both AccountHolderRenewalDate and a.AccountRenewalDate are strings. a.AccountRenewalDate holds the date I'm after.
What would I be doing wrong here?
This should do the trick - I'm assuming that your DB is a Date column so I didn't use DateTime.TryParse:
DateTime.Parse(AccountHolderRenewalDate).ToString("d");
If you want 09/01 instead of 9/1 use
.ToString("MM/dd/yyyy")
instead

Datetime conversion giving error

consider me a beginner in c#
I am doing some changes in a pre developed software (C#.Net) , we are saving data by datewise , Currently in insert query (build in c#) we are passing GETDATE() to save today date , but now we have to save data on the basis of a different date.
When I am building query in c# , I m passing that a datetime variable into query
after conversion , conversion as follow
Date_Stamp = DateTime.ParseExact(dt.Rows[0][0].ToString(), "MM/dd/yyyy HH:mm:ss tt", new CultureInfo("en-IN"));
but it is showing error "String was not recognized as a valid DateTime.".
The reason to convert is coz these date field are getting displayed in format ToString("yyyy-MM-dd"));
Which will give 2017-07-13 14:56:30.233 as 13-jul-2017 on front end (as per requirement). We cant change this part of code as it is being used in lot of places , hard to change .
Problem is
variable storing value as
2017-12-07 00:00:00.000
which give after conversion 07-Dec-2017 [wrong - it is needed as 12-jul-2017]
GETDATE storing value as
2017-07-12 14:56:30.233
which is after conversion coming right as 12-jul-2017
I know there is no datetime format in sql server when it come to storing data
But can we store value from variable [2017-12-07 ] as [2017-07-12 ] ?
How GETDATE() give us date in year-month-date format
?
Neither .NET's nor SQL Server's date related type have any format. All of them are binary values, just like integers and decimals. Formats apply only when they are explicitly or implicitly converted to strings, or parsed from strings.
Assuming your query looked something like SELECT GETDATE(), ... and you loaded the results to an DataTable, the values will be returned as DateTime values. If you used a strongly-typed DataTable you could just use the value. With a generic DataTable the value will be boxed and return as an object.
All you have to do is just cast the field value to DateTime :
Date_Stamp = (DateTime)dt.Rows[0][0];
This will also work for date and datetime2 types. datetimeoffset is returned as DateTimeOffset. time is returned as TimeSpan.
The problem in the original is caused because the field value is formatted into a string using the current culture dt.Rows[0][0].ToString() first. Then ParseExact is called trying to parse it using a different format. A simple DateTime.Parse(dt.Rows[0][0].ToString()) would have worked (even though it would be wasteful), since both DateTime.Parse and DateTime.ToString() use the same culture.
UPDATE
Reading date fields from a table has no issues - the values are returned using the appropriate date type. For example, running SELECT StartDate from ThatTable will return DateTime if the table's schema is :
CREATE TABLE ThatTable
(
ID int,
StartDate datetime
)
Problems are caused if, instead of using the correct type, dates are stored as strings in VARCHAR columns. That's a serious bug that needs to be fixed. There is NO assurance that the strings can be parsed to dates at all, or that they follow the same format. It's all too easy for some faulty application code to use eg DateTime.Now.ToString() and store a localized string in there.
Even if the format is the same, it's just wasteful and unreliable. The string takes more storage than the equivalent type, introduces conversion issues, prevents the use of date functions, and the server can't apply date optimizations to queries and indexing.

Convert date type in c# to match sql server 2008 date type

I have retrieved a date from an application and stored it in a DateTime Variable. The format of date is dd/mm/yyyy.
I now want to update a column (with datatype date (yyyy/mm/dd)) in a sql server 2008 database with this date
I have tried the below code, but it's giving me an exception "string was not recognized as valid datetime". Please help to solve this problem.
DateTime date = calExpirydate.SelectedDate;
DateTime date1 = DateTime.ParseExact(date.ToString(), "YYYY/MM/DD", CultureInfo.InvariantCulture);
You don't need to convert it at all if you use parameters (and you should be).
A rough example:
DateTime date = DateTime.Now;
SqlCommand command = new SqlCommand();
command.CommandText = "INSERT INTO table (date) VALUES (#date)";
command.Parameters.Add("#date",SqlDbType.DateTime).Value = date;
I'm using SQL Server here, however the concept is similar across most ADO.NET providers.
Your DateTime variable in the framework is stored in one basic format. The way it appears is just formatting off of the .ToString. It's saying give me your date bit make it look like this. Sql server is similar, it understands the date time variable regardless of how it appears.
If you pass your DateTime as exactly how it is in the framework it will save it correctly. The date and time isn't changing just how it's displayed. Your try parse isn't working though because it's not able to recognize the partial string you're giving it.
You don't even need a new date time variable to see it the way you want. Even if you're successful you will have identical date time variables.
yyyy/MM/dd should be correct
DateTime string format

Changing the format of DATETIME property in winform C#

What's wrong with this code?
Client c = new Client();
string format = "yyyy/MM/dd HH:mm:ss";
string dateAdded = now.ToString(format);
c.RegistrationDate = DateTime.Parse(dateAdded);
c.RegistrationDate is a dateTime object in the client class and I want it to insert to my database.
However It doesn't convert the freaking date to the format in my mysql database. It always says that string format is incorrect. WHAT have i done wrong???? should I convert my Registration Date to string??? Thanks
**EDIT: Sorry I've forgot to mention. "now" is now = DateTime.Now; it gets the current time of the date and time.
A DateTime doesnt have a format - it's just the date/time. (Whether it's local time, UTC or whatever is a different matter, mind you.)
Firstly, you shouldn't be converting to and from text like you are: that's just a recipe for trouble. Just use:
c.RegistrationDate = now;
... performing any rounding you need to.
You haven't shown how you're trying to insert the value into your database. If you're including the value in the SQL statement directly, that would explain it. You should be using a parameterized SQL statement and passing the value directly in the parameter - no conversion necessary.
If you're already doing that, please show us the code you're trying to use to insert the data, and we'll see what we can do. See the documentation for some examples.
I don't think there is anything wrong with the c# code,except I assume you must be doing
string dateAdded = DateTime.Now.ToString(format);
Otherwise I am not sure what 'now' is.

How to get datetime records in "dd/mm/yyyy h:m:s" format FROM SQL server 2005?

I want to get records from sql server 2005 in datetime format like this "dd/mm/yyyy h:m:s"
My database date is default datetime format
AttLogId int
...
DownloadLog datetime
I am trying to retrieve the datetime like this:
SELECT AttLogId ,convert(varchar,DownloadLogDate,103) FROM AttLog
ORDER BY DownloadLogDate
but I only get the date and not the time.
I suggest you don't try to get the values in a particular string format. Fetch them as DateTime values and then format them in the .NET code using DateTime.ToString("dd/MM/yyyy H:m:s").
It's almost always worth keeping data in its "natural" data type (date/time here) for as long as possible, only converting to text when you really need to. So your SQL should just be:
SELECT AttLogId, DownloadLogDate FROM AttLog
ORDER BY DownloadLogDate
How you then retrieve the data will depend on how you're talking to SQL (e.g. LINQ to SQL, using SqlDbReader etc). But you should be able to get it as a DateTime and then format it locally. This will make it easier to test, easier to debug, give you more control over cultural aspects (date separators, possibly specifying a standard specifier instead of a custom one, etc).
it is because you are using 103 , so it will give only date .
if you want more format check this :
http://msdn.microsoft.com/en-us/library/ms187928.aspx
According to need, u can try this
SELECT AttLogId , convert(varchar(10),DownloadLogDate,103) +' '+ convert(varchar(8),DownloadLogDate,108) FROM AttLog ORDER BY DownloadLogDate
Note : firstone is for date and second one is for time in H:M:S
hope this help u..

Categories